[英]How to add object in an array of objects using Javascript
I have the below JS object and I need to push another similar object with request.rules[0]
. 我有下面的JS对象,我需要使用
request.rules[0]
推送另一个类似的对象。
request : [
rules:
[
{
pageFilters:
[
{
matchType: 'contains',
type: 1,
value: 'a'
},
{
matchType: 'does not contain',
type: 1,
value: 'b'
}
],
name: 'TEST'
}
]
]
This is the object that I need to push to request.rules[1]: 这是我需要推送到request.rules [1]的对象:
{
pageFilters:
[
{
matchType: 'contains',
type: 1,
value: 'c'
},
{
matchType: 'does not contain',
type: 1,
value: 'd'
}
],
name: 'TEST 2'
}
This is what I've tried to implement, but it does not work ... 这是我尝试实现的方法,但是不起作用...
request.rules[1].pageFilters[0].push({
matchType: 'contains',
type: 1,
value: 'c'
})
request.rules[1].pageFilters[1].push({
matchType: 'contains',
type: 1,
value: 'd'
})
request.rules[1].name = "TEST 2";
This is the expected result: 这是预期的结果:
request :[
rules:
[
{
pageFilters:
[
{
matchType: 'contains',
type: 1,
value: 'a'
},
{
matchType: 'does not contain',
type: 1,
value: 'b'
}
],
name: 'TEST'
},
{
pageFilters:
[
{
matchType: 'contains',
type: 1,
value: 'c'
},
{
matchType: 'does not contain',
type: 1,
value: 'd'
}
],
name: 'TEST 2'
}
]
]
You do not have to push to a specific position eg request.rules[1].pageFilters[0], but rather to the array itself like this 您不必推送到特定位置,例如request.rules [1] .pageFilters [0],而是像这样推送到数组本身
var anotherFilter = {
matchType=contains,
type=1,
value=c
};
request.rules[1].pageFilters.push(anotherFilter);
With a proper object with request as object, 以一个以请求为对象的适当对象,
request: { // should be an object, not an array
rules: [
you could just use 你可以用
var object1 = { request: { rules: [{ pageFilters: [{ matchType: 'contains', type: 1, value: 'a' }, { matchType: 'does not contain', type: 1, value: 'b' }], name: 'TEST' }] } }, object2 = { pageFilters: [{ matchType: 'contains', type: 1, value: 'c' }, { matchType: 'does not contain', type: 1, value: 'd' }], name: 'TEST 2' }; object1.request.rules.push(object2); console.log(object1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我了解您的代码,{matchType = contains,type = 1,value = c}我见过{type:1,value:c}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.