【发布时间】:2019-05-27 05:15:09
【问题描述】:
我正在使用.map() 遍历数组数组,试图将内部数组作为key:value 对分配给对象。它不成功。这甚至可以工作吗?我需要把它分解成更多的步骤/功能/变量吗?
对于属性赋值中的元素,我已经尝试了所有我能想到的语法。
我还尝试对所有这些使用arr.map(function() {}) 语法,但没有区别。
const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = {};
const bigArr = [smallArr, thisArr, thatArr];
const newSomething = bigArr.map(arr => parentObj["arr"] = arr);
// parentObj returns: { arr: [ { key: 1, anotherKey: 2 } ] }
这两点我都懂。它正在分配我的元素的字符串 每次迭代并覆盖该值,以便最终对象为 一个键:值对,其中值是外部中的最后一个内部数组 数组。
const newSomething = bigArr.map(arr => parentObj.arr = arr);
//returns { arr: [ { key: 1, anotherKey: 2 } ] }
const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
//returns { arr: [ { key: 1, anotherKey: 2 } ] }
这个我不明白最后一对是怎么回事。
const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
// returns {
'1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ],
'5,4,65,24,35': [ 5, 4, 65, 24, 35 ],
'[object Object]': [ { key: 1, anotherKey: 2 } ],
arr: [ { key: 1, anotherKey: 2 } ]
}
这个我完全不懂。
const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
// returns {
'`${arr}`': [ { key: 1, anotherKey: 2 } ],
arr: [ { key: 1, anotherKey: 2 } ]
}
我正在尝试到达:
parentObj = {
smallArr: [1, 23, 25, 46, 52, 789, 64],
thisArr: [5, 4, 65, 24, 35],
thatArr: [{key: 1, anotherKey: 2}],
}
【问题讨论】:
-
您的数组只包含数组 - 它们不再命名为
smallArr、thisArr或thatArr。如果您只有bigArr,那么您需要明确拼出属性名称。
标签: javascript arrays object ecmascript-6