简体   繁体   中英

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.

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)

Run through Object.keys and reassign the values for each key from myArr .

 const myObj = { first: null, second: null, third: null }; const myArr = [ "abc", "def", "ghi"]; Object.keys(myObj).forEach((k,i)=>myObj[k]=myArr[i]); console.log(myObj);

Using switch to determine which object key to assign value to:

 const myArr = ["abc", "def", "ghi"]; const newObj = myArr.reduce((result, value, index) => { let key; switch (index) { case 0: key = "first"; break; case 1: key = "second"; break; case 2: key = "third"; break; } result[key] = value; return result; }, {}); console.log(newObj);

OR, for a more flexible option that does not rely on the descriptive key word:

 const myArr = ["abc", "def", "ghi", "jkl", "mno"]; const newObj = myArr.reduce((result, value, index) => { result[(index + 1).toString()] = value; return result; }, {}); console.log(newObj); /* { "1": "abc", "2": "def", "3": "ghi", "4": "jkl", "5": "mno" } */


Here's a SO solution that converts an integer to an ordinal , ie, 1 to "first", 2 to "second", etc.—up to "ninety-ninth". That gives you ordinal keys, and eliminates the need for the object myObj . By depending on myObj to provide the key names you'll need to predetermine how many elements are in myArr , and be sure there's a key in myObj for each.

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