Home > OS >  JS - From an object, return an object for each value of a certain key
JS - From an object, return an object for each value of a certain key

Time:09-16

From this object:

{"a": "a", "b": "b", "c": [1,2,3]}

I would like to get this:

{"a": "a", "b": "b", "c":1}
{"a": "a", "b": "b", "c":2}
{"a": "a", "b": "b", "c":3}

how can I do?

CodePudding user response:

You can map the data.c, and get the a, b from the origin object and c from the map callback item parameter.

const data = {"a": "a", "b": "b", "c": [1,2,3]}

const result = data.c.map(i => ({
  a: data.a,
  b: data.b,
  c: i,
}))


console.log(result)

CodePudding user response:

Map over object[c] and return the object a copy of the object itself the current value:

let expand = (obj, key) => obj[key].map(val => ({...obj, [key]: val}))

test = {"a": "a", "b": "b", "c": [1,2,3]}
result = expand(test, 'c')
console.log(result)

CodePudding user response:

First, you should check if that the obj[key] is an array. If it is, continue with mapping, else just return the object

const transform = (obj, key) => {
  if (!Array.isArray(obj[key])) return obj

  return obj[key].map(val => ({ ...obj, [key]: val }))
}

console.log(transform({ a: "a", b: "b", c: "c" }, "c"))
console.log(transform({ a: "a", b: "b", c: [1, 2, 3] }, "c"))
console.log(transform({ a: "a", b: "b", d: [4, 5, 6] }, "d"))

  • Related