[英]Adding objects to array object
I'm trying to add objects to an existing array if the condition is true. 如果条件为真,我正在尝试将对象添加到现有数组。
Below is my code 以下是我的代码
RequestObj = [{
"parent1": {
"ob1": value,
"ob2": {
"key1": value,
"key2": value
},
},
},
{
"parent2": {
"ob1": value,
"ob2":{
"key1":value,
"key2": value
}
}
}]
Here I'm trying to add an object to the RequestObj
array if the condition is true. 这里我试图在条件为真的情况下向
RequestObj
数组添加一个对象。 I could do RequestObj.push()
. 我可以做
RequestObj.push()
。 But i don't know how to added in parent1
object. 但我不知道如何在
parent1
对象中添加。
if (key3 !== null) {
// add this below object to parent1 object
"ob3": {
"key1": value,
"key2": value
}
}
I'm not able to find any solution. 我无法找到任何解决方案。 Please help
请帮忙
The way to add an element to an array is to push
it. 向元素添加元素的方法是
push
它。
// Create new object
var newObject = {
"ob3": {
"key1": value,
"key2": value
}
};
// Add new object to array
RequestObj.push(newObject);
You can also directly push an object into the array without declaring a variable first: 您也可以直接将对象推入数组而不首先声明变量:
// Add new object to array
RequestObj.push({
"ob3": {
"key1": value,
"key2": value
}
});
UPDATE UPDATE
If you are not pushing into the array but adding a new property to an object inside the array, you need to know the position of the element inside the array, like RequestObj[0]
for the first element. 如果您没有推入数组但是向数组内的对象添加新属性,则需要知道数组内元素的位置,例如第一个元素的
RequestObj[0]
。
Then within that element, you need to add a new property to the parent1
object ( RequestObj[0].parent1
): 然后在该元素中,您需要向
parent1
对象添加一个新属性( RequestObj[0].parent1
):
RequestObj[0].parent1.ob3 = {
"key1": "A",
"key2": "B"
};
var RequestObj = [{ "parent1": { "ob1": "A", "ob2": { "key1": "B", "key2": "C" }, }, "parent2": { "ob1": "D", "ob2": { "key1": "E", "key2": "F" } } }]; var key3 = 'somethingNotNull'; if (key3 !== null) { RequestObj[0].parent1.ob3 = { "key1": "A", "key2": "B" }; } console.log(RequestObj);
You shoud iterate RequestObj
in loop and find object by key parent1
. 你应该循环迭代
RequestObj
并按键parent1
查找对象。
For that you can use .filter
function like this: 为此你可以像这样使用
.filter
函数:
for(let i = 0; i < RequestObj.lenght; i++) {
let found_object = RequestObj[i].filter(function (r) {
return r == 'parent1'
});
}
Then you can execute operations over found_object
. 然后,您可以通过
found_object
执行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.