How do you create an new array, with same objects but with extra properties. Sample below creates a new array with a subset of properties. But I try to do is create some new properties on existing objects. So result will be objects from accounts.data, with an extra property called test.
var options = accounts.data.map((o) => ({
label: o.name,
value: o.id,
number: o.accountNumber,
test: o.name o.id
}))
CodePudding user response:
Try this
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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can do that using 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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>