I want to convert an object into an array of object but my code give the wrong result like shown below..
// object
data = { user_id : '123' }
// expected result
data = [ { user_id : '123' } ]
// what I get instead
data = [ { v : '123' } ]
my code:
let arr = [];
Object.keys(data).map(v => {
console.log(v, data[v]); // here it shows 'user_id' and '123' as it's supposed to
arr.push({ v:data[v] }); // but here it uses the 'v' as property instead of 'user_id'
});
>Solution :
You need to put v inside a square bracket
const data = {
user_id: '123'
}
let arr = [];
Object.keys(data).map(v => {
arr.push({
[v]: data[v]
});
});
console.log(arr)
Alternatively you can also use Object.entries. You dont need initialize let arr = []; as map will create a new array
const data = {
user_id: '123'
}
const arr = Object.entries(data).map(v => {
return {
[v[0]]: v[1]
}
});
console.log(arr)