【问题标题】:Filter array with object that contains array [closed]使用包含数组的对象过滤数组[关闭]
【发布时间】:2017-07-18 18:43:08
【问题描述】:

我怎样才能做到这一点

var foo = [{
  "number":[1, 2, 3],
  "id": [81, 82, 83]
}];

进入这个

var foo = [{
  "number": 1,
  "id": 81
},{
  "number": 2,
  "id": 82
},{
  "number": 3,
  "id": 83
}]

我尝试了.map().filter(),但结果并不符合我的需要。有什么建议么?谢谢

【问题讨论】:

  • 至少发布您的代码
  • 你从哪里得到填充foo 的数据,为什么它被包装在一个外部数组中?这看起来像an XY problem,并且可能有一个解决您真正问题的方法,而不涉及像这样进行奇怪的对象操作。
  • 为什么foo 是一个数组?
  • “有什么建议吗?” ...是的,告诉我们你的尝试。 Stackoverflow 的目标是帮助您修复您的代码而不是免费的代码编写或教程服务
  • 抓取第一个项目,然后是第一个键。通过遍历键将这些数组值映射到对象中。

标签: javascript arrays function object


【解决方案1】:

你可以为此创建一个函数:

function transform(values) {
  const result = [];
  values.forEach(value => {
    value.id.forEach((id, i) => {
      result.push({id, number: value.number[i]});
    });
  });
  return result;
}

【讨论】:

    【解决方案2】:

    虽然我觉得这是一个奇怪的问题,并且我仍然希望得到关于我怀疑是 an XY problem 的回应,但这里有一种可能的方法,你可以用它来做任何你想做的事情。

    假设foo 是一个对象,它只包含可枚举的属性,这些属性都是等长的数组:

    var foo = {
      "number": [1, 2, 3],
      "id": [81, 82, 83]
    }
    
    function spread(obj) {
      // get the enumerable keys of your object
      var keys = Object.keys(obj)
      // initialize an empty array
      var array = []
    
      // for each key...
      keys.forEach(function (key) {
        // for each element in the array of the property...
        obj[key].forEach(function (value, index) {
          // if the array element does not contain an object
          // initialize an empty object in index
          var base = index < array.length ? array[index] : (array[index] = {})
    
          // assign the value to the key in the element
          base[key] = value
        })
      })
    
      // return the generated array
      return array
    }
    
    console.log(spread(foo))

    【讨论】:

      【解决方案3】:

      您可以将数组的对象和每个对象的数字数组映射到一个新数组中,然后将结果合并以将子数组展平为一个数组。

      var foo = [{
        "number":[1, 2, 3],
        "id": [81, 82, 83]
      }];
      
      var result = [].concat.apply([], foo.map(function(obj) { // map the array into sub arrays and flatten the results with concat
        return obj.number.map(function(n, i) { // map the number array
          return {
            number: n,
            id: obj.id[i] // get the id value by using the index
          };
        })
      }));
      
      console.log(result);

      【讨论】:

        【解决方案4】:

        您需要根据给定键中值的数量创建对象列表。

        因此,您需要遍历对象的主列表。在该循环中,您需要遍历一个键的值(即选择第一个)。您不需要直接使用这些值,它们只是确定将在最终数组中创建多少条记录。最后,您只需再次遍历键并根据当前索引映射键值对。

        最后发生的Array.prototype.concat.apply([], ...arrays) 将合并所有数组。

        该函数支持单个对象或对象列表。

        var foo = [{
          "number" : [ 1,  2,  3],
          "id"     : [81, 82, 83]
        }, {
          "number" : [ 4,  5,  6],
          "id"     : [84, 85, 86]
        }];
        
        console.log(JSON.stringify(mapValues(foo), null, 4));
        
        function mapValues(arr) {
          arr = !Array.isArray(arr) ? [arr] : arr;
          return Array.prototype.concat.apply([], arr.map(item => {
            return item[Object.keys(item)[0]].map((val, index) => {
              return Object.keys(item).reduce((obj, key) => {
                obj[key] = item[key][index];
                return obj;
              }, {});
            });
          }));
        }
        .as-console-wrapper { top: 0; max-height: 100% !important; }

        这是另一个没有引入太多复杂性的版本。

        var foo = [{
          "number" : [1, 2, 3],
          "id"     : [81, 82, 83]
        }, {
          "number" : [4, 5, 6],
          "id"     : [84, 85, 86]
        }];
        
        console.log(JSON.stringify(mapValues(foo), null, 4));
        
        function mapValues(arr) {
          arr = !Array.isArray(arr) ? [arr] : arr;
          let records = [], fields;
          arr.forEach(item => {
            fields = fields || Object.keys(item);
            item[fields[0]].forEach((val, index) => {
              records.push(fields.reduce((obj, key) => {
                obj[key] = item[key][index];
                return obj;
              }, {}));
            });
          });
          return records;
        }
        .as-console-wrapper {
          top: 0;
          max-height: 100% !important;
        }

        结果

        [{
            "number": 1,
            "id": 81
        }, {
            "number": 2,
            "id": 82
        }, {
            "number": 3,
            "id": 83
        }, {
            "number": 4,
            "id": 84
        }, {
            "number": 5,
            "id": 85
        }, {
            "number": 6,
            "id": 86
        }]
        

        【讨论】:

          猜你喜欢
          • 2019-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-15
          • 2017-01-28
          • 2021-08-28
          • 1970-01-01
          • 2014-03-20
          相关资源
          最近更新 更多