我正在从一个对象创建一个新数组。我用一个 for 循环来做到这一点。
for (var key in data["record"])
{
if (data["record"].hasOwnProperty(key))
{
if (data["record"][key]["acquisition.method"] != undefined ) {
newObject[key] = [];
newObject[key]["acquisition.method"] = data["record"][key]["acquisition.method"][0];
if (data["record"][key]["production.date.end"] != undefined ) {
newObject[key]["production.date"] = data["record"][key]["production.date.end"][0];
}
}
}
}
该数组在 console.log 中如下所示:
0: Array[0]
1: Array[0]
2: Array[0]
3: Array[0]
4: Array[0]
5: Array[0]
我想让它像这样:
record: Array[0]
record: Array[0]
record: Array[0]
record: Array[0]
record: Array[0]
我该怎么做?
添加了 JSON
newObject = [
"record": [
"something": "value",
"somethingelse": "value"
],
"record": [
"something": "value",
"somethingelse": "value"
],
"record": [
"something": "value",
"somethingelse": "value"
],
"record": [
"something": "value",
"somethingelse": "value"
]
]
我唯一能做到的是这样的:
newObject = [
"0": [
"something": "value",
"somethingelse": "value"
],
"1": [
"something": "value",
"somethingelse": "value"
],
"2": [
"something": "value",
"somethingelse": "value"
],
"3": [
"something": "value",
"somethingelse": "value"
]
]
我尝试过这样的事情,但我知道 push 仅适用于数组:
var newObject = {};
var records ={};
records["record"] = {};
for (var key in data["record"])
{
if (data["record"].hasOwnProperty(key))
{
if (data["record"][key]["acquisition.method"] != undefined ) {
records["record"]["acquisition.method"] = data["record"][key]["acquisition.method"][0];
if (data["record"][key]["production.date.end"] != undefined ) {
records["record"]["production.date"] = data["record"][key]["production.date.end"][0];
newObject.push(records);
}
}
}
}
我现在尝试的:
var records =[];
var newObject1 = {};
var newObject2= {};
for (var key in data["record"])
{
if (data["record"].hasOwnProperty(key))
{
if (data["record"][key]["acquisition.method"] != undefined ) {
newObject2["acquisition.method"] = data["record"][key]["acquisition.method"][0];
if (data["record"][key]["production.date.end"] != undefined ) {
newObject2["production.date"] = data["record"][key]["production.date.end"][0];
newObject1["record"] = newObject2;
}
}
}
records.push(newObject1);
}