Tengo una matriz de objetos, cada objeto tiene un objeto anidado que necesito modificar.
Ejemplo: Lo que tengo abajo
const array = [{ asset: {key: '1235', type: 'mocFirst'}, id: 27, marketValuey: 6509, marketValueySecond: 65033, marketValueyThird: 650900, }]quiero conseguir eso:
const array = [{ type: 'mocFirst' key: '1235', id: 27, marketValuey: 6509, marketValueySecond: 65033, marketValueyThird: 650900, }]ahí está mi solución
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}; });¿Alguna cosa sobre mi solución? ¿Quizás se puede hacer mejor? En producción, tendré una gran variedad
Aquí tienes, es una solución recursiva para aplanar el objeto.
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);Yo usaría un concepto de desestructuración.
array.map((elem) => { const { id, marketValuey, marketValueySecond, marketValueyThird, asset: {key}, asset: {type} } = elem; return { id, marketValuey, marketValueySecond, marketValueyThird, key, type } })para un concepto más detallado de desestructuración, consulte - desestructuración anidada
Simplemente aplanarlo así:
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 })