![](/img/trans.png)
[英]Order of the associative array in JavaScript by key and access by index
[英]check if key index exists in an associative array Angularjs javascript
从下面的 json 数据如何检查“no_2”的键“type_1”是否存在,如果不存在推送{"p_id": "24","subcat_id": "2","name": "ok"}
到“ no_2”数组 object 的“type_1”。
键索引和数组推送如何在这里工作
{
"no_1": {
"orderNumber": "no_1",
"billing_order_id": "1",
"orderArray": {
"type 2": [
{
"p_id": "25",
"subcat_id": "2",
"name": "fine"
},
{
"p_id": "34",
"subcat_id": "2",
"name": "not ok"
}
]
}
},
"no_2": {
"orderNumber": "no_2",
"billing_order_id": "1",
"orderArray": {
"type_1": [
{
"p_id": "6",
"subcat_id": "1",
"name": "hello"
}
]
}
}
}
我认为这就是你想要做的。
(大多数 JavaScript 代码的结构并不完全如此,但为了清楚起见,示例代码很冗长。)
const myObj = getObj(), keyToCheck = "no_3", myArr = [], myKeys = Object.keys(myObj), // `.keys` is as static method of Object keyToPush = myKeys[0], // gets first key in list valueToPush = myObj[keyToPush], // gets value from this key in obj fullObjToPush = {}; // makes a new empty object fullObjToPush[keyToPush] = valueToPush; // Makes a new property in obj w/ key and val // pushes object to array if `keyToCheck` is not found if(myKeys.includes(keyToCheck)){ /* do nothing */ } else{ myArr.push(fullObjToPush); } // prints result console.log("myArr now contains this object:"); console.log(myArr); // provides original object function getObj(){ return { "no_1": { "orderNumber": "no_1", "billing_order_id": "1" }, "no_2": { "orderNumber": "no_2", "billing_order_id": "1" } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.