我有这样的数据集:
[
{
"_id": "5aa7b6add9655d0bd4ce1f53",
"user_name": "as",
"createdate": "2018-03-13T11:31:57.133Z",
},
{
"_id": "5aa7b6add9655d0bd4ce1f54",
"user_name": "ds",
"createdate": "2018-03-13T11:31:57.133Z",
},
]
现在为了逐个获取值,我创建了一个循环。在循环下我得到了价值。
Now if I want to add extra key value on that object then how it will be done.?
我试过数据[i] .extrakey =“value”; 的console.log(数据); 但它不会设置。
非常感谢任何帮助
答案 0 :(得分:2)
使用map
array = array.map( s => Object.assign( s, {extrakey : "value" } ) );
答案 1 :(得分:0)
您可以在下面的示例中看到它。只是迭代数组并添加一个新键将改变数组中的对象,因为object是一个引用类型,你只是使用一个更改原始对象的引用。
const array = [
{
"_id": "5aa7b6add9655d0bd4ce1f53",
"user_name": "as",
"createdate": "2018-03-13T11:31:57.133Z",
},
{
"_id": "5aa7b6add9655d0bd4ce1f54",
"user_name": "ds",
"createdate": "2018-03-13T11:31:57.133Z",
}
];
array.forEach(item => item.extraKey = 'value');
console.log(array);
此外,如果您想更改数组项,最好不要更改原始对象,而是创建副本并提供新数组。
const array = [
{
"_id": "5aa7b6add9655d0bd4ce1f53",
"user_name": "as",
"createdate": "2018-03-13T11:31:57.133Z",
},
{
"_id": "5aa7b6add9655d0bd4ce1f54",
"user_name": "ds",
"createdate": "2018-03-13T11:31:57.133Z",
}
];
const newArray = array.map(item => Object.assign({}, item, { extraKey: 'value' }));
console.log(newArray);
答案 2 :(得分:0)
您可以使用spread
和array.prototype.map
添加额外的密钥:
var arr = [
{
"_id": "5aa7b6add9655d0bd4ce1f53",
"user_name": "as",
"createdate": "2018-03-13T11:31:57.133Z",
},
{
"_id": "5aa7b6add9655d0bd4ce1f54",
"user_name": "ds",
"createdate": "2018-03-13T11:31:57.133Z",
},
];
var result = arr.map(e => ({...e, extraKey: 'value'}));
console.log(result);
答案 3 :(得分:0)
var array = [
{
"_id": "5aa7b6add9655d0bd4ce1f53",
"user_name": "as",
"createdate": "2018-03-13T11:31:57.133Z",
},
{
"_id": "5aa7b6add9655d0bd4ce1f54",
"user_name": "ds",
"createdate": "2018-03-13T11:31:57.133Z",
}
];
array = array.map( s => Object.assign( s, {extrakey : "value" } ) );