Home > Software design >  How to find an object by value in a multi level json array
How to find an object by value in a multi level json array

Time:08-04

I have a json array, where I would like to find an item name and get the itemcat returned in javascript.

    "Allitems":[
      {"item":["APPLE IPHONE 13 PRO 256GB"], "itemcat": "Preorder"},
      {"item":["Samsung Galaxy S9  64GB","Samsung Galaxy S22", "Apple iPhone XR 256GB"], "itemcat": "Phones"}
]

currently I read the value that I want to search from a website using cypress

      cy.get(`.basket-body > :nth-child(${p}) > :nth-child(1) > > :nth-child(1) > `)
                            .invoke('text')
                            .then(text => {
                                cy.wait(600)
                                cy.log(text)

How could I pass (text) through a find function to get the corresponding itemcat value returned. as the second item has more then 1 value that it should match search.

Thanks

CodePudding user response:

I assume you want to match by text as the item?

var obj = {
  "Allitems": [{
      "item": ["APPLE IPHONE 13 PRO 256GB"],
      "itemcat": "Preorder"
    },
    {
      "item": ["Samsung Galaxy S9  64GB", "Samsung Galaxy S22", "Apple iPhone XR 256GB"],
      "itemcat": "Phones"
    }
  ]
}
var text = "Samsung Galaxy S22";

function find_cat(text, obj) {
  var cat = obj.Allitems.find(function(sub) {
    return sub.item.indexOf(text) >= 0
  })
  return (cat ? cat.itemcat : null)
}

console.log(find_cat(text, obj)) 

  • Related