【问题标题】:How to modify an array and convert it to JSON如何修改数组并将其转换为 JSON
【发布时间】:2018-08-18 14:05:21
【问题描述】:

我有一个数组:

[ 'Item 1', 'Item 2', 'Item 3' ]

我需要最终的结果是

{ 'Item 1':true, 'Item 2':true, 'Item 3':true }

使用 ES6 我有点接近这个:

        let arr = [];
        for (let m of crmData.modRequired) {
            let i = m + ':true';
            arr.push(i);
        }
        modReq = JSON.stringify(arr);
        modReq = modReq.replace(/\[/, '{');
        modReq = modReq.replace(/\]/, '}');

但这产生了: {"Quotes:true","Flight Logs:true","Currency Records:true","FTD:true","Maintenance Tracker:true"}

【问题讨论】:

  • 嗯...好吧,不要。将其转换为数组,基于它创建一个新对象,然后对其进行字符串化。
  • 右:将数组映射成对象数组,然后通过JSON.stringify()

标签: javascript arrays json ecmascript-6


【解决方案1】:

您可以使用Object.assignArray.map 轻松做到这一点,如下所示:

这个想法是将您的值数组映射到遵循{"ItemX": true} 模式的对象数组中,然后使用Object.assign 将它们组合成一个对象。

var items = ["Item 1", "Item 2", "Item 3"];

var mapped = Object.assign({}, ...items.map(item => ({[item]: true})));

console.log(JSON.stringify(mapped));

【讨论】:

    【解决方案2】:

    您应该可以使用数组.reduce 方法来执行此操作。这会将数组变成你想要的对象。然后你可以使用JSON.stringify 将它转换成一个json字符串。

    const myArray = [ 'Item 1', 'Item 2', 'Item 3' ]
    
    // I need the final result to be
    // { 'Item 1':true, 'Item 2':true, 'Item 3':true }
    
    const myObj = myArray.reduce((obj, key) => {
      obj[key] = true;
      return obj;
    }, {});
    
    console.log("javascript object:", myObj);
    console.log("json string:", JSON.stringify(myObj))

    【讨论】:

    • 我可能不会使用.reduce(),但这并不意味着这是一个糟糕的答案。为什么投反对票?
    • @Pointy 很好奇你为什么不使用.reduce()。从技术上讲,它不是算法效率最高的吗?
    • 你是对的;我可能会使用.reduce() - 我想我在输入时对 OP 想要什么感到困惑。
    • 比使用 Object.assign 和扩展运算符更优雅的解决方案。如果使用旧浏览器,也更容易填充。
    • @David784 不确定我会说“更优雅”,更高效 - 是的。兼容旧版浏览器 - 是的。但是,OP 在原始问题的代码中具有 ES6 语法,因此可以安全地假设他们已经在使用 polyfill,或者不关心支持旧版浏览器。
    【解决方案3】:

    只需在循环数组时构建对象(一步),您无需替换任何大括号或方括号。

    var ary = [ 'Item 1', 'Item 2', 'Item 3' ];
    var obj = {};
    ary.forEach(function(itm) { obj[itm] = true; } );
    console.log(obj);
    objJSON = JSON.stringify(obj);
    console.log(objJSON);

    【讨论】:

      【解决方案4】:

      将函数reduceSpread Syntax一起使用

      var array = [ 'Item 1', 'Item 2', 'Item 3' ],
          result = array.reduce((a, c) => ({...a, ...{[c]: true}}), {});
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      使用forEach

      var array  = [ 'Item 1', 'Item 2', 'Item 3' ],
          result = {};
      
      array.forEach(c => result[c] = true);
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案5】:

        使用 .forEach

        let arr = [ 'Item 1', 'Item 2', 'Item 3' ];
        let newArr = {};
        arr.forEach(item=>{
          newArr[item] = true;
        });
        console.log(newArr);

        不过我更喜欢mhodges 答案:

        let arr = [ 'Item 1', 'Item 2', 'Item 3' ];
        console.log(Object.assign({}, ...arr.map(item => ({[item]: true}))))

        【讨论】:

        • 您的结果似乎格式不正确(我认为)。 OP 想要一个带有每个键的对象,而不是单独的这些对象的数组。
        • 哦,我明白了,已修复。
        猜你喜欢
        • 2018-12-12
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 2019-04-17
        相关资源
        最近更新 更多