I have an array of objects each object has one nested object I need to modify that
Example: What I have below
const array = [{
asset: {key: '1235', type: 'mocFirst'},
id: 27,
marketValuey: 6509,
marketValueySecond: 65033,
marketValueyThird: 650900,
}]
I want get that:
const array = [{
type: 'mocFirst'
key: '1235',
id: 27,
marketValuey: 6509,
marketValueySecond: 65033,
marketValueyThird: 650900,
}]
There is my solution
const array = [{
asset: {key: '1235', type: 'mocFirst'},
id: 27,
marketValuey: 6509,
marketValueySecond: 65033,
marketValueyThird: 650900,
},
{
asset: {key: '12', type: 'mocFirst44'},
id: 27,
marketValuey: 6409,
marketValueySecond: 64033,
marketValueyThird: 640900,
},
{
asset: {key: '1299', type: 'mocFirst'},
id: 271,
marketValuey: 6109,
marketValueySecond: 61033,
marketValueyThird: 610900,
},
{
asset: {key: '1296', type: 'mocFirst'},
id: 272,
marketValuey: 65092,
marketValueySecond: 650332,
marketValueyThird: 6509020,
},
]
const resultArr = array.map(item => {
const { asset, ...newObj} = item;
const { key, type } = item.asset;
return { key, type, ...newObj};
});
Any things about my solution? Maybe it can be done better? In production, I will have a big array
Here you go, it's a recursive solution to flatten the object
function flat(source, target) {
Object.keys(source).forEach(function(k) {
if (source[k] !== null && typeof source[k] === 'object') {
flat(source[k], target);
return;
}
target[k] = source[k];
});
}
const array = [{
asset: {
key: '1235',
type: 'mocFirst'
},
id: 27,
marketValuey: 6509,
marketValueySecond: 65033,
marketValueyThird: 650900,
},
{
asset: {
key: '12',
type: 'mocFirst44'
},
id: 27,
marketValuey: 6409,
marketValueySecond: 64033,
marketValueyThird: 640900,
},
{
asset: {
key: '1299',
type: 'mocFirst'
},
id: 271,
marketValuey: 6109,
marketValueySecond: 61033,
marketValueyThird: 610900,
},
{
asset: {
key: '1296',
type: 'mocFirst'
},
id: 272,
marketValuey: 65092,
marketValueySecond: 650332,
marketValueyThird: 6509020,
},
]
let flatArr = array.map(item => {
let flatObj = {};
flat(item, flatObj);
return flatObj
});
console.log(flatArr);
I would use a concept of destructuring.
array.map((elem) => {
const {
id,
marketValuey,
marketValueySecond,
marketValueyThird,
asset: {key},
asset: {type}
} = elem;
return {
id,
marketValuey,
marketValueySecond,
marketValueyThird,
key,
type
}
})
for more detailed concept of destructuring refer - nested-destructuring
Just flatten it out like so:
var outArr = array.map(item => {
// Create the new items
item.key = item.asset.key
item.type = item.asset.item
// Delete the old parent
delete item.asset
return item
})