Skip to content Skip to sidebar Skip to footer

Js - Check Item Exist Before Pushing In Array

I've unformatted JSON structured key-value pair data. I need to format it and returned it into another formatted structured.so, Sample Code:: // Unformatted data like this, which c

Solution 1:

This might help

If(keyArray.indexOd(i) == -1) { valueArray.push(i) }

Or just need to update

const newValueKey = {};

for (let i = 0; i < keys.length; i++) {
  if (!newValueKey[keys[i]]) newValueKey[keys[i]] = { data: [] };
  newValueKey[keys[i]].data.push(values[i]);
}

Solution 2:

Only need to conditionally assign the value as an array or concat it with the existing value depending if the value on key exists.

For simplicity, if the key will only contain an array of string it is not necessary nesting it into another object: newObj.fuits={data:[...]} should be newObj.fruits=[...]

// Unformatted data like this, which contains repeating keyslet query = {
    "junk,fruit,vegetable,junk,fruit": "pizza,apple,potato,burger,mango"
  }


// formatting like this,const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");

const newObj = {}

for (let i = 0; i < keys.length; i++) {
   let key=keys[i]
   let value=values[i]
   newObj[key] = newObj[key] ? [...newObj[key],value] : [value]
}

console.log(newObj)

/*
{
  "junk": [
    "pizza",
    "burger"
  ],
  "fruit": [
    "apple",
    "mango"
  ],
  "vegetable": [
    "potato"
  ]
}
*/

Post a Comment for "Js - Check Item Exist Before Pushing In Array"