[英]How to add an object.key to an existing array in javascript?
I would like to add a new object.key to my JSON array.我想在我的 JSON 数组中添加一个新的 object.key。
To do that I have defined a new variable var result = {"bad":1}
then I'm pushing the items like this skippedData.push(item.metadata["pico:record"]["dc:description"],{result});
为此,我定义了一个新变量
var result = {"bad":1}
然后我推送这样的项目skippedData.push(item.metadata["pico:record"]["dc:description"],{result});
As JSON output I'm having:作为 JSON output 我有:
[
{
"skippedData": [
{
"_": "Lungo le mura, al posto del baluardo nord-est, la cosiddetta Fortezza medicea è un degradato complesso di corpi di fabbrica eretti nella 2ª metà del '500 attorno al trecentesco cassero senese.",
"$": {
"xml:lang": "it"
}
},
{
"result": {
"bad": 1
}
}
]
}
]
Which is wrong since I'm having a new "result" object instead of a "result" object key.这是错误的,因为我有一个新的“结果” object 而不是“结果” object 密钥。
My expected output should be:我预期的 output 应该是:
[
{
"skippedData": [
{
"_": "Lungo le mura, al posto del baluardo nord-est, la cosiddetta Fortezza medicea è un degradato complesso di corpi di fabbrica eretti nella 2ª metà del '500 attorno al trecentesco cassero senese.",
"$": {
"xml:lang": "it"
},
"result": {
"bad": 1
}
}
]
}
]
What I'm doing wrong?我做错了什么?
Regards问候
skippedData
is an array. skippedData
是一个数组。 You are using push method which is adding elements to array.您正在使用将元素添加到数组的push 方法。
As I understood u want to add data from two sources in one object, so u can use this way to build new object there with spread :据我了解,您想将来自两个来源的数据添加到一个 object 中,因此您可以使用这种方式在其中构建新的 object 并扩展:
skippedData.push({
...item.metadata["pico:record"]["dc:description"],
...{result}
});
or equal with Object.assign或等于Object.assign
skippedData.push(Object.assign(
{},
item.metadata["pico:record"]["dc:description"],
{result}
));
If u want exactly to modify object already existing in array, u can refer to it by key, eg如果你想精确修改数组中已经存在的object,你可以按键引用,例如
skippedData[0].result = result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.