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.
CodePudding user response:
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)
CodePudding user response:
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, i.e., 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.
CodePudding user response:
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);