如何创建一个新的数组,相同的对象,但有额外的属性。下面的示例创建了一个包含属性子集的新数组。但我尝试做的是在现有对象上创建一些新属性。因此结果将是来自帐户的对象。数据,带有一个名为test.
的额外属性var options = accounts.data.map((o) => ({
label: o.name,
value: o.id,
number: o.accountNumber,
test: o.name+o.id
}))
试试这个
const accounts = {
data: [{
name: 'Test 1',
id: 0,
number: "123456-10",
otherProperty: "Hello World!"
},
{
name: 'Test 2',
id: 1,
number: "123456-11",
otherProperty: "Hello World!!"
},
]
};
const options = accounts.data.map((account) => ({ ...account,
test: account.name + account.id
}));
console.log(options)
可以使用object。assign
const accounts = {
data: [
{
name: 'Test 1',
id: 0,
number: "123456-10",
otherProperty: "Hello World!"
},
{
name: 'Test 2',
id: 1,
number: "123456-11",
otherProperty: "Hello World!!"
},
]
}
var options = accounts.data.map((o) => Object.assign({},o, {
label: o.name,
value: o.id,
number: o.accountNumber,
test: o.name+o.id
}))
console.log(options);