Skip to content
Advertisement

js: fill object with array elements using reduce()

trying to learn reduce() but can’t understand it well yet. Maybe someone from you could help me with my problem.

I have an object with defined keys and an array. I would like to fill up the objects keys with the arrays values using reduce().

My sandbox LINK

Till now I tried something like this:

const myObj = {
  first: null,
  second: null,
  third: null
}

const myArr = [ "abc", "def", "ghi"]

const newObj = myArr.reduce((result, value, index) => {
  result[index] = value
  return result
}, myObj)

console.log(newObj)
// 0: "abc"
// 1: "def"
// 2: "ghi"
// first: null
// second: null
// third: null

expected result:

{
  first: "abc",
  second: "def",
  third: "ghi"
}

Thanks for any help.

Advertisement

Answer

You need to change index into “an object key at index“:

const newObj = myArr.reduce((result, value, index) => {
    result[Object.keys(myObj)[index]] = value
    return result
}, myObj)

That said, zip + Object.fromEntries would be more appropriate for the job:

const zip = (...args) => args[0].map((_, i) => args.map(a => a[i]));

const myObj = {
    first: null,
    second: null,
    third: null
}

const myArr = [ "abc", "def", "ghi"]

const result = Object.fromEntries(
    zip(
        Object.keys(myObj),
        myArr
    )
)

console.log(result)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement