-3

I have an objects that contains arrays with following structure:

var obj  = {
  "feature1" : ["val1","val2"],
  "feature2" : ["val3"]
}

Now I want to split the values that are present inside of this each array and form a new array of objects that should like :

var result = [
  {
    "field": "feature1",
    "value": "val1",
    "type": "add"
  },
  {
    "field": "feature1",
    "value": "val2",
    "type": "add"
  },
  {
    "field": "feature2",
    "value": "val3",
    "type": "add"
  }
]

Here splitting must happen based on the "field" and it show something that is similar to above.here "type" is an extra field that is hardcoded

Help would be appreciated.

joy08
  • 9,004
  • 8
  • 38
  • 73

1 Answers1

0

You can get key/value pairs, loop over them, then loop over each value in each array, and push each value into an object, back into the accumulator

var obj = {
  "feature1": ["val1", "val2"],
  "feature2": ["val3"]
}

const output = Object.entries(obj)
  .reduce((a, [k, v]) => a
    .concat(v
      .map(e => ({
        field: k,
        value: e,
        type: 'add'
      })
    )
  ), [])


console.log(output)

Or, as a one-line less readable version:

var obj = {
  "feature1": ["val1", "val2"],
  "feature2": ["val3"]
}

const output = Object.entries(obj).reduce((a, [k, v]) => a.concat(v.map(e => ({field: k, value: e, type: 'add'}))), [])

console.log(output)

For a more performance-oriented solution, you should use plain old for loops:

var obj = {
  "feature1": ["val1", "val2"],
  "feature2": ["val3"]
}

const out = []

for (var o in obj) {
  const arr = obj[o]
  for(var i = 0; i < arr.length; i++) {
    out.push({
      field: o,
      value: arr[i],
      type: 'add'
    })
  }
}

console.log(out)

Here is a JSPerf to show the performance difference JSPerf


Edit:

var obj = {
  "feature1": ["1", "1", "2", "3", "1"],
  "feature2": ["val3"]
}

const output = Object.entries(obj).reduce((a, [k, v]) => a.concat([...new Set(v)].map(e => ({field: k, value: e, type: 'add'}))), [])

console.log(output)
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • Thank you . It worked. How can I avoid duplicate values , if there is one under that field? Say there is something "feature1" : ["1","2","1"], Do not want multiple values of 1 – joy08 Jul 24 '19 at 11:57
  • 1
    @vrosario You could use a set to remove them, I'll add an edit now. – Kobe Jul 24 '19 at 12:21