我想要做的非常简单,并且有一个我无法理解的语法错误:
我有一个包含一些对象的数组,我想使用这些对象的一些值创建另一个数组:
let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
let respone = []
// different implementation
fields.map(item => {
respone.push({item.label: ''}) } )
`Uncaught SyntaxError: Unexpected token .`
fields.map(item => {
respone = [...response, {item.label: ''}] } )
`Uncaught SyntaxError: Unexpected token .`
fields.map(item => {
respone = [...response, {item['label']: ''}] } )
`Uncaught SyntaxError: Unexpected token [`
显然错误来自创建对象
{item['label']: ''}
.这些错误的原因是什么,以及从现有对象值创建新对象的最佳方法是什么。
最佳答案
所以你有一个对象数组,由 type
组成和 label
.您想使用该数组制作一个“复合对象”。首先,你不想要 respone
要成为一个数组,你希望它是一个对象。其次,您要命名 respone
上的 key 为 item.label
的值.
试试这个代码:
let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
// Create an empty object
let respone = {}
// Iterate over the fields array, using each one to set the key and value
// on our respone object.
fields.forEach(item => { respone[item.label] = item.type} );
// Let's see how it looks!
console.log(respone);
编辑 : 根据评论,使用
.map()
没有任何意义-- 这样做的目的是根据数组值返回一个新数组,通常是转换后的数据。在这种情况下,使用 Array.forEach(...)
更有意义。 , 代码已修改为此。
关于javascript - 从js中另一个对象的值创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380425/