Skip to content
Advertisement

Push data inside an array index. React Native JSX

I am trying to compare, find and push data inside an array. But getting following error

Error => TypeError: undefined is not an object (evaluating ‘data[index].push’)

I have following JSON/Array

[
  {
     "category":"Super",
     "id":"1",
     "images":[],
     "status":"open",
     "url":"some url here"
  },
  {
     "category":"Pizza",
     "entitlement_id":"pizza_pack_ent",
     "id":"2",
     "images":[],
     "package_id":"pizza_pack_single",
     "status":"locked",
     "url":"some url here"
  }
]

I want to push packages object inside matching category so json/array will be as follows

[
  {
     "category":"Super",
     "id":"1",
     "images":[],
     "status":"open",
     "url":"some url here"
  },
  {
     "category":"Pizza",
     "entitlement_id":"pizza_pack_ent",
     "id":"2",
     "images":[],
     "package_id":"pizza_pack_single",
     "status":"locked",
     "url":"some url here",
     "packages": [
         {
           "id":"abcds"
         },
         {
            "id": "xyz"
         }
      ]
  }
]

Following is the code what I was trying to do:

data.forEach((category, index) => { //data is main json/array in which I want to push packages
       packages.forEach((pckg, idx) => {
            if(pckg.identifier === category.package_id){
              // data[category].push(pckg); //not worked
              data[index].push(pckg); //not worked either
            }
                
        })
 })
 console.log(data);

Advertisement

Answer

I don’t know how your packages array look like, but this should give you the expected result:

data.forEach((category, index) => { //data is main json/array in which I want to push packages
       packages.forEach((pckg, idx) => {
            if(category.package_id  && pckg.identifier === category.package_id){
              if (!category.packages) {
                  category.packages = [];
              }
                category.packages.push(pckg)
            }
                
        })
 })
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement