通过将嵌套属性提升到一个级别来转换javascript对象

时间:2017-11-23 07:51:21

标签: javascript ecmascript-6

我无法将嵌套值移动到一个级别。我想将name属性移动到一个级别,如何转换此

[{
    date: "1/11",
    collections: [{
        device: {name: "camera 1"},
        count: 10
    },{
        device: {name: "camera 2"},
        count: 20
    },{
        device: {name: "camera 3"},
        count: 30
    }]
}]

到此?

[{
    date: "1/11",
    data: [{
        camera: "camera 1",
        count: 10
    },{
        camera: "camera 2",
        count: 20
    },{
        camera: "camera 3",
        count: 30
    }]
}]

我被困在http://jsfiddle.net/usjyc83u/

2 个答案:

答案 0 :(得分:1)

您需要映射数组,然后映射内部集合数组。

注意:此解决方案使用proposal-object-rest-spread,需要Babel的Object rest spread transform才能正常工作。



const data = [{"date":"1/11","collections":[{"device":{"name":"camera 1"},"count":10},{"device":{"name":"camera 2"},"count":20},{"device":{"name":"camera 3"},"count":30}]}];

const result = data.map(({ collections, ...o }) => ({
  ...o,
  data: collections.map(({ device, ...r }) => ({
    ...r,
    camera: device.name
  }))
}));

console.log(result);




答案 1 :(得分:1)

我不确定你的主要对象是数组还是简单对象。我已将您的对象视为数组。我做的是

  1. 映射全局集合(=" 对数组中的每个元素执行此操作")
  2. 为每个对象创建一个新密钥:data。它的值是一个数组
  3. 使用collections中的对象作为所需结构中的对象填充数据数组({camera: ..., count:...}
  4. 从对象中删除collections。 (如果你想保留它,那么删除该行)
  5. 
    
    const yourData = [{
      date: "1/11",
      collections: [{
        device: {
          name: "camera 1"
        },
        count: 10
      }, {
        device: {
          name: "camera 2"
        },
        count: 20
      }, {
        device: {
          name: "camera 3"
        },
        count: 30
      }]
    }];
    
    // using ES5+ syntax
    // 1. map through your objects
    yourData.map(el => {
      // 2. set data array
      el.data = [];
      // 3. populate with required objects in correct structure
      el.collections.forEach(o => {
        el.data.push({
          camera: o.device.name,
          count: o.count
        });
      });
      // 4. remove the old data
      delete el.collections;
    });
    
    console.log(yourData);
    
    [{ date: "1/11", data: [{ camera: "camera 1", count: 10 },{ camera: "camera 2", count: 20 },{ camera: "camera 3", count: 30 }] }]