【问题标题】:Assigning key's to array objects将键分配给数组对象
【发布时间】:2020-03-02 02:44:24
【问题描述】:

我正在尝试解决这个问题。本质上,我有一个键数组和对象内的一个值数组,我希望这些值有键。

以下是我迄今为止最好的尝试——通常使用 python,所以这对我来说有点混乱。

var numbers = [3, 4, 5,6]

var selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]]
var result = [];

for (arr in selection) {
numbers.forEach(function (k, i) {
result[k] = arr[i]
})
};

console.log(result);

我要找的输出是这样的,

results = [{3:1,4:2,5:3,6:4}, {..},..]

喜欢一些获得正确输出的指针。

注意。这是给谷歌应用脚​​本的!所以不能使用某些javascript函数(我认为MAP不起作用,不确定减少)。

干杯!

【问题讨论】:

    标签: javascript arrays json google-apps-script


    【解决方案1】:

    创建一个单独的函数,将键和值作为参数,并使用reduce() 将其转换为对象。然后在selections 上应用map() 并使用该函数为每个子数组创建一个对象

    var numbers = [3, 4, 5,6]
    var selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]]
    
    function makeObject(keys, values){
      return keys.reduce((obj, key, i) => ({...obj, [key]: values[i]}),{});
    }
    const res = selection.map(x => makeObject(numbers, x));
    console.log(res)

    【讨论】:

      【解决方案2】:

      在选择时使用map,在选择时使用Object.assign

      var numbers = [3, 4, 5, 6];
      
      var selection = [
        [1, 2, 3, 4],
        [6, 5, 4, 3],
        [2, 9, 4]
      ];
      
      var result = selection.map(arr =>
        Object.assign({}, ...arr.map((x, i) => ({ [numbers[i]]: x })))
      );
      
      console.log(result);

      【讨论】:

        【解决方案3】:

        从头开始为每个数字数组创建一个new 对象:

        const selection = [
          [1, 2, 3, 4],
          [6, 5, 4, 3],
          [2, 9, 4],
        ];
        
        function objMaker(numarr) {
          const numbers = [3, 4, 5, 6];
          numarr.forEach((num, i) => (this[numbers[i]] = num));
        }
        console.info(selection.map(numarr => new objMaker(numarr)));

        【讨论】:

          猜你喜欢
          • 2017-12-08
          • 1970-01-01
          • 2010-11-22
          • 2017-12-10
          • 1970-01-01
          • 2015-07-15
          • 1970-01-01
          • 1970-01-01
          • 2017-06-29
          相关资源
          最近更新 更多