简体   繁体   English

检查关联数组中是否存在键索引 Angularjs javascript

[英]check if key index exists in an associative array Angularjs javascript

From the below json data how can I check if key "type_1" of "no_2" exists, if doesnt exists to push {"p_id": "24","subcat_id": "2","name": "ok"} to the "type_1" of "no_2" array object.从下面的 json 数据如何检查“no_2”的键“type_1”是否存在,如果不存在推送{"p_id": "24","subcat_id": "2","name": "ok"} no_2”数组 object 的“type_1”。

How does key index and array push works here键索引和数组推送如何在这里工作

{
  "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"
        }
      ]
    }
  }
}

I think this is what you're trying to do.我认为这就是你想要做的。
(Most JavaScript code is not structured quite this way, but the sample code is verbose for clarity.) (大多数 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM