【问题标题】:Convert set of object's into array item将一组对象转换为数组项
【发布时间】:2016-12-08 07:30:53
【问题描述】:

我有几个这样的对象:

{'id[0]': 2}
{'url[0]': 11}
{'id[1]': 3}
{'url[1]': 14}

我想得到这样的东西:

[{id:2, url:11}, {id:3, url:14}]

我的项目中也有 lodash。也许 lodash 对此有一些方法?

【问题讨论】:

  • 我认为我们需要使用正则表达式解析对象的键。
  • 你是如何携带这几件物品的
  • @Viplock 在手。
  • 您是否要合并每两个对象?
  • @guest271314 不,也许他正在尝试使用此 [0][1] 进行合并

标签: javascript ecmascript-6 lodash


【解决方案1】:

您可以对键使用正则表达式并在必要时创建一个新对象。然后将值分配给键。

var data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }],
    result = [];

data.forEach(function (a) {
    Object.keys(a).forEach(function (k) {
        var keys = k.match(/^([^\[]+)\[(\d+)\]$/);
        if (keys.length === 3) {
            result[keys[2]] = result[keys[2]] || {};
            result[keys[2]][keys[1]] = a[k];
        }
    });
});

console.log(result);

【讨论】:

    【解决方案2】:

    这是一个基于@NinaScholz solution的ES6解决方案。

    我假设每个对象只有一个属性,就像问题中提出的那样。

    1. 使用Object#assign 将对象数组合并为一个大对象,并使用Object.entries 转换为条目。
    2. 使用Array#reduce 迭代数组。
    3. 使用array destructuring从每个条目中提取原始键值。
    4. 使用正则表达式和数组提取所需的键和索引 解构。
    5. 然后使用object spread 在索引处创建/更新新对象。

    const data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }];
    
    // combine to one object, and convert to entries
    const result = Object.entries(Object.assign({}, ...data)) 
      // extract the original key and value
      .reduce((r, [k, value]) => {
        
        // extract the key and index while ignoring the full match
        const [, key, index] = k.match(/^([^\[]+)\[(\d+)\]$/);
    
        // create/update the object at the index
        r[index] = {...(r[index] || {}), [key]: value }; 
    
        return r;
      }, []);
    
    console.log(result);

    【讨论】:

      【解决方案3】:

      var arr = [{'id[0]': 2},
      {'url[0]': 11},
      {'id[1]': 3},
      {'url[1]': 14}];
      
      var result = [];
      
      arr.forEach(function(e, i, a){
        var index = +Object.keys(e)[0].split('[')[1].split(']')[0];//get the number inside []
        result[index] = result[index] || {}; //if item is undefined make it empty object 
        result[index][Object.keys(e)[0].split('[')[0]] = e[Object.keys(e)[0]];//add item to object
      })
      
      console.log(result);

      【讨论】:

        【解决方案4】:

        您可以使用 for 循环、.filter()RegExp 构造函数和参数 "\["+i+"\]" 其中 i 是当前索引,Object.keys().reduce().replace()RegExp@987653

        var obj = [{
          "id[0]": 2
        }, {
          "url[0]": 11
        }, {
          "id[1]": 3
        }, {
          "url[1]": 14
        }];
        
        var res = [];
        for (var i = 0; i < obj.length / 2; i++) {
          res[i] = obj.filter(function(o) {
                     return new RegExp("\[" + i + "\]").test(Object.keys(o))
                   })
                   .reduce(function(obj, o) {
                     var key = Object.keys(o).pop();
                     obj[key.replace(/\[\d+\]/, "")] = o[key];
                     return obj
                   }, {})
        }
        
        console.log(res);

        【讨论】:

          猜你喜欢
          • 2018-11-24
          • 2021-12-13
          • 1970-01-01
          • 2021-05-03
          • 2018-12-04
          • 2021-06-16
          • 1970-01-01
          相关资源
          最近更新 更多