-1

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.

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"
        }
      ]
    }
  }
}
Steffi
  • 255
  • 1
  • 3
  • 14

1 Answers1

0

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.)

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" }
  }
}
Cat
  • 4,141
  • 2
  • 10
  • 18