将键移到子数组js

时间:2018-12-14 11:30:50

标签: javascript arrays ecmascript-6

我有一个按名称分组的对象数组,如下所示:

[
  {
    Name: 'Color',
    Data:[{Id: 1, Name: 'Red'},
          {Id: 2, Name: 'Yellow'},
          {Id: 3, Name: 'Blue'},
          {Id: 4, Name: 'Green'},
          {Id: 7, Name: 'Black'}]
  }, {
    Name: 'Size',
    Data:[{Id: 8, Name: 'S'},
          {Id: 11, Name: 'M'},
          {Id: 12, Name: 'L'},
          {Id: 13, Name: 'XL'},
          {Id: 14, Name: 'XXL'}]
  }
]

我想将其转换为如下所示的重数组:

[
  {Id: 1, Name: 'Red', optionName: 'Color'}, 
  {Id: 2, Name: 'Yellow', optionName: 'Color'},
  {Id: 3, Name: 'Blue', optionName: 'Color'},
  {Id: 4, Name: 'Green', optionName: 'Color'},
  {Id: 7, Name: 'Black', optionName: 'Color'},
  {Id: 8, Name: 'S', optionName: 'Size'},
  {Id: 11, Name: 'M', optionName: 'Size'},
  {Id: 12, Name: 'L', optionName: 'Size'},
  {Id: 13, Name: 'XL', optionName: 'Size'},
  {Id: 14, Name: 'XXL', optionName: 'Size'}
]

如何在javascript / ES6中做到这一点?

3 个答案:

答案 0 :(得分:0)

您可以使用.map().concat()Object.assign()方法来获得结果数组:

let data = [
  {Name: 'Color', Data:[{Id: 1, Name: 'Red'}, {Id: 2, Name: 'Yellow'}, {Id: 3, Name: 'Blue'}, {Id: 4, Name: 'Green'}, {Id: 7, Name: 'Black'}]},
  {Name: 'Size', Data:[{Id: 8, Name: 'S'}, {Id: 11, Name: 'M'}, {Id: 12, Name: 'L'}, {Id: 13, Name: 'XL'}, {Id: 14, Name: 'XXL'}]}
];

let result = [].concat(
  ...data.map(({Name, Data}) => Data.map(o => Object.assign({}, o, {optionName: Name})))
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以将array#reducearray#forEach一起使用。

const data = [ { Name: 'Color', Data:[{Id: 1, Name: 'Red'}, {Id: 2, Name: 'Yellow'}, {Id: 3, Name: 'Blue'}, {Id: 4, Name: 'Green'}, {Id: 7, Name: 'Black'}] }, { Name: 'Size', Data:[{Id: 8, Name: 'S'}, {Id: 11, Name: 'M'}, {Id: 12, Name: 'L'}, {Id: 13,Name: 'XL'}, {Id: 14, Name: 'XXL'}] } ],
      result = data.reduce((r, {Name: optionName,Data}) => {
        Data.forEach(({Id, Name}) => r.push({Id,Name, optionName}));
        return r;
      }, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您也可以使用forEach进行操作。如下所示。

var s = [{Name:'Color',Data:[{Id:1,Name:'Red'},{Id:2,Name:'Yellow'},{Id:3,Name:'Blue'},{Id:4,Name:'Green'},{Id:7,Name:'Black'}]},{Name:'Size',Data:[{Id:8,Name:'S'},{Id:11,Name:'M'},{Id:12,Name:'L'},{Id:13,Name:'XL'},{Id:14,Name:'XXL'}]}];

var y=[];

s.forEach(x=>x.Data.forEach(z=>{
  z['optionName'] = x.Name;
  y.push(z);
}));

console.log(y);