简体   繁体   中英

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 contains repeating keys

  let 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++) {
   newObj[keys[i]] = values[i]
}

console.log(newObj)

//[ junk:pizza and fruit:apple are not returned in console]

//Output:
// {junk:  'burger',
// fruit: 'mango',
// vegetable: 'potato'}

JSON, doesn't allow repeating keys that's why its not returned.That's why I'm trying to returned it in another structure.

For doing that, if the key is repeating then push its value into same data of array as shown in Expected Output.

newObj.includes('junk') or newObj.includes('mango') , with this, it can be checked if that particular key already present in output or not or in an array.

I want to returned my Output: like this

{
    'junk': {
     'data': [
       'pizza', 
       'burger'
      ]
    }, 
    'fruit': {
     'data': [
       'apple',
       'mango'
     ]
    },
    'vegetable': {
     'data': [
        'potato'
      ]
    }
}        

JSFiddle Link: https://jsfiddle.net/sophia22134/0yLxowt4/

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]);
}

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 keys let 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" ] } */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM