从动态数组中拉出对象并转换为对象数组

时间:2018-03-19 13:34:39

标签: javascript arrays object

我有一个特定的案例,我甚至不知道是否有可能实现。

给定输入数组。

var originalArr = [
  [
    { ID: 3, name: 'Beef' },
    { ID: 4, name: 'Macaroni' },
    { ID: 5, name: 'Sauce#1' }
  ],
  [{ ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' }]
];

我想迭代内部数组并从对象中选择ID然后创建一个新数组代替数组。所以我的输出看起来应该是这样的。

var output = [
  {
    '1': {
      name: 'Lettuce',
      ID: 1
    },
    '2': {
      name: 'Brocoli',
      ID: 2
    }
  },
  {
    '3': {
      name: 'Beef',
      ID: 3
    },
    '4': {
      name: 'Macaroni',
      ID: 4
    },
    '5': {
      name: 'Sauce#1'
    }
  }
];

使用map迭代内部数组很容易,但是如何创建新的Object代替数组并动态提取其键值?如果输入产生所需的输出,它甚至是可能的。

3 个答案:

答案 0 :(得分:4)

Use map and reduce

originalArr.map( s => //iterate outer array
    s.reduce( (acc, c) => (  //iterate inner array using reduce
       acc[c.ID] = c, acc  //assign the id as key to accumulator and return the accumulator
    ) , {}) //initialize accumulator to {}
)

Demo

var originalArr = [
  [
    { ID: 3, name: 'Beef' },
    { ID: 4, name: 'Macaroni' },
    { ID: 5, name: 'Sauce#1' }
  ],
  [{ ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' }]
];

var output = originalArr.map( s => s.reduce( (acc, c) => ( acc[c.ID] = c, acc ) , {}) );

console.log(output);

答案 1 :(得分:1)

您可以使用纯javascript

来实现递归
var originalArr = [
        [{
            ID: 3,
            name: 'Beef'
        }, {
            ID: 4,
            name: 'Macaroni'
        }, {
            ID: 5,
            name: 'Sauce#1'
        }],
        [{
            ID: 1,
            name: 'Lettuce'
        }, {
            ID: 2,
            name: 'Brocoli'
        }]
    ]

    function bindInObject(object, array) {
        for (var i = 0; i < array.length; i++) {
            var it = array[i];
            if (it instanceof Array) {
                bindInObject(object, it);
            } else {
                var id = it.ID;
                object[id] = it;
            }
        }
    }
    var output = {};

    bindInObject(output, originalArr);
    console.log(output) 

答案 2 :(得分:0)

const original_array = [
[
    { ID: 3, name: 'Beef' },
    { ID: 4, name: 'Macaroni' },
    { ID: 5, name: 'Sauce#1' }
],
[
    { ID: 1, name: 'Lettuce' },
    { ID: 2, name: 'Brocoli' }
]
]

let new_array = []

for (let i=0; i < original_array.length; i++) {
    if (original_array[i + 1]) new_array = 
    new_array.concat(original_array[i].concat(original_array[i+1]))
}

let output = []

for (let i=0; i<new_array.length; i++) {
    output.push({[new_array[i].ID]: new_array[i]})
}