Home > Net >  Node js Json checking if a specific key and value exists and then getting its value
Node js Json checking if a specific key and value exists and then getting its value

Time:10-25

the following JSON is returned to me from the API

[
  {
    type: 'atom',
    id: 'atom',
    atom: { type: 'priceWithTitle', priceWithTitle: [Object] }
  },
  {
    type: 'atom',
    id: 'atom',
    atom: { type: 'price', price: [Object] }
  },
  {
    type: 'atom',
    id: 'name',
    atom: { type: 'textAtom', textAtom: [Object] }
  },
  { atom: { type: 'labelList', labelList: [Object] } }
]

Briefly how do I get this data:

......

const JsonFromApi = JSON.parse(DataFromApi)
console.log(JsonFromApi)

// After that I get Json from above

To refer to a specific group of elements, I need to specify it. For example, in order to get the block I need (which contains the price, it is the second in a row), I need to specify [1], for example

console.log(JsonFromApi[1]) // After that I get the element I need, below will be the json i get:
{
  type: 'atom',
  id: 'atom',
  atom: {
    type: 'price',
    price: {
      price: '532 $',
      priceColor: 'amTextSecondary',
      originalPriceColor: 'amTextSecondary',
      theme: 'STYLE_TYPE_MEDIUM',
      strikethroughColor: 'amAccentAlert'
    }
  }
}

So what's the problem?

The JSON that is returned to me from the API can change the order of the elements inside, for example, now I applied for the price of a product using [1], another time or with another product, the element will be [2], [3] or another.

Question - : How to get the data I need if the order of the elements is constantly changing, the only clue is -> atom: { type: 'price', price: [Object] }

type: contains type information about the type of data inside, How do I first check which element contains the type I need and then get its value, for example -> get the price of the goods?

CodePudding user response:

You can use the function hasOwnProperty() on the atom object

const object = [
  {
    type: "atom",
    id: "atom",
    atom: { type: "priceWithTitle", priceWithTitle: [Object] },
  },
  {
    type: "atom",
    id: "atom",
    atom: { type: "price", price: [Object] },
  },
  {
    type: "atom",
    id: "name",
    atom: { type: "textAtom", textAtom: [Object] },
  },
  { atom: { type: "labelList", labelList: [Object] } },
];

function checkPrice(object) {
  object.forEach((element) => {
    if (element.atom.hasOwnProperty("price")) {
      console.log(element.atom.price);
    }
  });
}
  • Related