如何用新特性展平下芯对象

How to Flatten Object Underscore with a new Property?

本文关键字:对象 何用新      更新时间:2023-09-26

我有一个这样的数组:

var arr = [
   {
    name: 'John',
    age: {
        id: 1,
        value: 'less than 19'
      }
   },
   {
    name: 'Doe',
    age: {
         id: 2,
         value: 'more than 19'
      }
   }
]

如何使用下划线来展平数组中的年龄对象。预期结果是:

arr == [
       {
        name: 'John',
        age: 'less than 19'
       },
       {
        name: 'Doe',
        age: 'more than 19'
       }
    ];

谢谢,

你可以试试这个:

var result = arr.map(function(item) {
    return {
        name: item.name,
        age: item.age.value
    };
});

演示:

var arr = [{
  name: 'John',
  age: {
    id: 1,
    value: 'less than 19'
  }
}, {
  name: 'Doe',
  age: {
    id: 2,
    value: 'more than 19'
  }
}];
var result = arr.map(function(item) {
  return {
    name: item.name,
    age: item.age.value
  };
});
console.log(result);

我希望这对你有帮助。

使用旧样式:D

var arr = [
   {
    name: 'John',
    age: {
        id: 1,
        value: 'less than 19'
      }
   },
   {
    name: 'Doe',
    age: {
         id: 2,
         value: 'more than 19'
      }
   }
];
var newArr = [];
arr.forEach(function(item, idx) {
  newArr.push({
    name: item.name,
    age: item.age.value
  });
});
console.log(newArr);