2017-10-16 83 views
4

我想谈谈这个:如何变换数组对象

let myArray = [ {city: "NY"}, {status: 'full'} ]; 

这样:

let myObj = { city: "NY", status: 'full' }; 

而我尝试这样做:

let newObj = {}; 
for (var i = 0; i < myArray.length; i++) { 
    (function(x) { 
    newObj = Object.assign(myArray[i]); 
    })(i); 
} 

它分配最后一对对象

+1

你请求的对象是无效的;你不能有'{{city:'NY'}}' –

回答

11

Spread中的数组转换成Object#assign

const myArray = [ {city: "NY"}, {status: 'full'} ]; 
 

 
const myObj = Object.assign({}, ...myArray); 
 

 
console.log(myObj);

:分配到一个空对象。如果你省略了空对象,原始数组的第一个元素将会发生变异(所有东西都会被合并到它中)。

+0

是的,这就是我的意思。这是一个错误 –

+2

值得注意的是,扩展运算符在IE 11 – zfrisch

+1

中不可用,那么为扩展语法使用“Object.assign”是没有意义的,这在IE11中是不可用的。 –

2

我会倾向于与Ori你的问题似乎是有关创建索引对象通常不是一个很好的计划达成一致,但如果有必要的与数字键,在对象,你可以做这样的:

let newObj = {}; 
myArray.forEach((val, index) => { newObj[index] = val }); 
+0

是的,这就是我的意思。这是一个错误 –

1
let myArray = [ {city: "NY"}, {status: 'full'} ]; 

let newObj = myArray.reduce((acc, curr) => { 
    Object.keys(curr).forEach(val => { 
    acc[val] = curr[val] 
    }) 
    return acc 
}, {}) 

console.log(newObj) 

此语法在IE根据caniuse.com支持

+0

没有任何上下文的代码blob不是最好的答案。请考虑扩展此。即使在问题的背景下,也不清楚“IE支持”的含义。 – jdv

+0

'map'不使用结果只是迭代数组的坏模式。你可以使用'forEach'。 –

2

您也可以使用Array.reduce()这将给你更多的精细控制:

const myArray = [ 
 
    { city: "NY", color: 'blue', rodents: { small: false, medium: false, large: true } }, 
 
    { status: 'full', color: 'red' }, 
 
    { sandwich: 'flavourful' } 
 
] 
 
    
 
// item is each object in your array 
 
const reduced = myArray.reduce((newObj, item) => { 
 
    // existing props will be overwritten by newer object entries in the array 
 
    // this example is same as Object.assign spread with right to left precedence, 
 
    // until you want more custom logic 
 
    Object.keys(item).forEach((key) => newObj[key] = item[key]) 
 
    return newObj 
 
}, {}) 
 
    
 
console.log(reduced)

相关问题