【问题标题】:Assigning a variable name as an object property while using Array.prototype.map使用 Array.prototype.map 时将变量名称分配为对象属性
【发布时间】: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}],
}

【问题讨论】:

  • 您的数组只包含数组 - 它们不再命名为 smallArrthisArrthatArr。如果您只有bigArr,那么您需要明确拼出属性名称。

标签: javascript arrays object ecmascript-6


【解决方案1】:

您可以简单地使用对象字面量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)

【讨论】:

    【解决方案2】:

    只需显式分配每个变量:

    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; }

    【讨论】:

    • 我不是故意的,我试图检查两个答案,因为它们是相同的,我猜当我检查第二个答案时它低估了你的答案
    • 没关系 - 你可以接受另一个@DoubleBridges。先不接受我的。
    猜你喜欢
    • 2016-06-30
    • 2011-02-17
    • 2017-12-04
    • 2011-11-29
    • 2013-11-23
    • 2013-06-19
    • 2010-10-16
    • 1970-01-01
    相关资源
    最近更新 更多