将其他元素添加到现有JSON数组中

时间:2018-04-18 05:06:55

标签: arrays json typescript

我有一个案例,我想在TypeScript中将元素添加到JSON数组中,如下所示

[ 
{
"a" : "a1",
"b" : "b1"
}
]

现在我想在不创建新块的情况下为上述对象添加值,例如,我想将键值对添加为“C”:“c1”和“d”:“d1”。执行此操作后,我的JSON数组必须如下所示

[ 
{
"a" : "a1",
"b" : "b1"
"c" : "c1",
"d" : "d1"
}
]

我尝试了什么:

let someData : any [] = [];

someData.push({
"a" : "a1",
"b" : b1"
})

someData.push({
"c" : "c1",
"d" : d1"
})

但是它创建了两个如下所示的记录,但这是错误的

[ 
{
"a" : "a1",
"b" : "b1"
}
{
"c" : "c1",
"d" : "d1"
}
]

我也尝试使用unshift,如下所示

someData.unshift({
"c" : "c1",
"d" : d1"
})

这是将结果对象返回为

[ 
{
"a" : "a1",
"b" : "b1"
}
{
"c" : "c1",
"d" : "d1"
}
]

有什么办法吗?

例如,

for(int i =0; i<3; i++){
  someData.push({
    i : i+1
})

但是上面的代码块正在创建错误的数组结构,但我想要如下所示

{
0 :1,
1:2,
2:3
}
}

4 个答案:

答案 0 :(得分:2)

它应该是这样的......

let someData : any [] = [];

someData.push({
"a" : "a1",
"b" : b1"
})

someData[0]["c"] = "c1";
someData[0]["d"] = "d1";

因此,当您记录someData的值时......它将显示

console.log(someData); //[{"a":"a1","b" : "b1", "c":"c1", "d":"d1"}]

用于循环遍历值...

let valuesToPut = [["c","c1"],["d","d1"]];

 for(let i = 0; i < valuesToPut.length; i++){
    someData[0][valuesToPut[i][0]] = valuesToPut[i][1]
 }

答案 1 :(得分:1)

正如您所说,它是一种数组json格式。

因此,如果访问数组中的某个元素,则应指明数组索引。

前:

let tempArray = [ 
{
"a" : "a1",
"b" : "b1"
}
]  

=&GT; tempArray [0]有这个值。

{
"a" : "a1",
"b" : "b1"
}

因此,如果你向tempArray [0]添加一些额外的值,你应该访问如下的元素:

tempArray[0]['c'] = "c1";
tempArray[0]['d'] = "d1";

答案 2 :(得分:1)

ObjectArray之间几乎没有混淆,在这里您尝试将一些项添加到存储在数组索引0上的Object

让我们尝试以下代码:

let someData : any [] = [];
// Create first index of array and create on it your Object.
someData.push({
    "a" : "a1",
    "b" : b1"
});

// Override first index of array by merge of previous data + new one.
someData[0] = Object.assign(someData[0], {
    "c1" : "c1",
    "d1" : "d1"
});

Object assign documentation

Another way to do this: Object.defineProperties()

答案 3 :(得分:1)

&#13;
&#13;
//Let's start with what you're doing
let someData = [];

someData.push({
"a" : "a1",
"b" : "b1"
});
// pushes a collection of 2 key value pairs in as the first entry to someData
someData.push({
"c" : "c1",
"d" : "d1"
});
// pushes a collection of 2 key value pairs in as the second entry to someData
console.log(someData);

// what you might want to do:
someData = [];

someData.push({
"a" : "a1",
"b" : "b1"
});
// pushes a collection of 2 key value pairs in as the first entry to someData
someData[0].c = "c1";
//Sets a value to the key c in the first element of some data
someData[0].d = "d1";
//Sets a value to the key d in the first element of some data
console.log(someData)

// What you probably want to do.
someData = {};
for(let i of [1,2,3,4]){
  someData[String.fromCharCode(i+96)] = String.fromCharCode(i+96)+"1";
}
console.log(someData)
&#13;
&#13;
&#13;