用新对象创建一个数组

时间:2018-04-29 19:54:41

标签: javascript arrays object

我想根据“value1”,“value2”和“value3”的值创建新对象

 myArray = [{fruit: "apple", value1: 3, value2:2, value1 :1}] 

我想要的结果是

myNewArray = [ {fruit: "apple", item: "value1"},{fruit: "apple", item: "value1"},{fruit: "apple", item: "value1"},{fruit: "apple", item: "value2"},{fruit: "apple", item: "value2"},{fruit: "apple", item: "value3"}] 

2 个答案:

答案 0 :(得分:1)

使用Array.map()迭代外部数组,使用对象destructuring with restfruit与值分开。使用Object.entries()获取值键/值对,并使用Array.map()进行迭代。对于每个值,使用Array.from()生成一个新的对象数组,其值为length,密钥为itemSpread进入Array.concat()以展平每次使用Array.map时生成的子阵列:



const myArray = [{fruit: "apple", value1: 3, value2:2, value3 :1}];

const result = [].concat(...myArray.map(({ fruit, ...values }) => 
  [].concat(...Object.entries(values)
    .map(([item, length]) => Array.from({ length }, () => ({
      fruit,
      item
    })))
)));

console.log(result);




答案 1 :(得分:0)

尝试以下代码:

var myArray = [{fruit: "apple", value1: 3, value2:2, value3 :1}] 

var myNewArray = []
function insertItem (ct, itemName, fruit) {
    var itemArr = [];
    for(var i=0;i< ct;i++){
        var newItem = {fruit};
        newItem['item'] = itemName;
        itemArr.push(newItem);
    }
    return itemArr;
}
myArray.forEach(function (obj) {
    myNewArray.push(...insertItem(obj.value1, 'value1', obj.fruit));
    myNewArray.push(...insertItem(obj.value2, 'value2', obj.fruit));
    myNewArray.push(...insertItem(obj.value3, 'value3', obj.fruit));
})

console.log(myNewArray);