使用Array.prototype.map时将变量名称分配为对象属性

时间:2019-05-27 05:15:10

标签: javascript arrays object ecmascript-6

我正在使用.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}],
}

2 个答案:

答案 0 :(得分:3)

您可以简单地使用对象文字shorthand property

let smallArr = [1, 23, 25, 46, 52, 789, 64];
let thisArr =  [5, 4, 65, 24, 35];
let thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr,}

console.log(parentObj)

答案 1 :(得分:0)

只需显式分配每个变量:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr };

console.log(parentObj);
.as-console-wrapper { max-height: 100% !important; top: auto; }

以上是以下简称:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr: smallArr, thisArr: thisArr, thatArr: thatArr };

console.log(parentObj);
.as-console-wrapper { max-height: 100% !important; top: auto; }

相关问题