[英]js: fill object with array elements using reduce()
试图学习 reduce() 但还不能很好地理解它。 也许你的某个人可以帮助我解决我的问题。
我有一个带有定义键和数组的对象。 我想使用 reduce() 用数组值填充对象键。
我的沙盒LINK
直到现在我尝试了这样的事情:
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
预期结果:
{
first: "abc",
second: "def",
third: "ghi"
}
谢谢你的帮助。
您需要将index
更改为“ index
处的对象键”:
const newObj = myArr.reduce((result, value, index) => {
result[Object.keys(myObj)[index]] = value
return result
}, myObj)
也就是说, zip
+ Object.fromEntries
更适合这项工作:
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)
运行Object.keys
并从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);
使用switch
来确定将值分配给哪个对象key
:
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);
或者,对于不依赖于描述性关键字的更灵活的选项:
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" } */
这是一个将整数转换为序数的 SO 解决方案,即将 1 转换为“第一”,将 2 转换为“第二”,等等——直到“第九十九”。 这为您提供了序号键,并消除了对对象myObj
的需要。 通过依赖myObj
提供键名,您需要预先确定myArr
中有多少元素,并确保myObj
中每个元素都有一个键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.