如何从javascript中的对象数组映射多个属性

IT技术 javascript arrays object filter javascript-objects
2021-01-29 00:00:07

我有一个 Object 数组,如下所示:

var obj = [
  {a: 1, b: 5, c: 9},
  {a: 2, b: 6, c: 10},
  {a: 3, b: 7, c: 11},
  {a: 4, b: 8, c: 12}
];

我知道如何Array.map()像这样使用单个对象

var result = obj.map(x=>x.a)

这会给我以下结果

[1, 2, 3, 4]

但我想要的结果如下:

[
  {a: 1, b: 5},
  {a: 2, b: 6},
  {a: 3, b: 7},
  {a: 4, b: 8}
]

简而言之,从对象数组中我只想选择几个字段(多个)

怎么做 ?

6个回答

您可以.map()对象解构一起使用

let data = [
    {a:1,b:5,c:9}, {a:2,b:6,c:10},
    {a:3,b:7,c:11}, {a:4,b:8,c:12}
];
          
let result = data.map(({ a, b }) => ({a, b}));

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

如果像您的示例一样,您想排除一个或几个特定属性,则可以使用解构并使用其余属性来创建仅包含您想要的属性的对象:

var obj = [
  {a:1,b:5,c:9},
  {a:2,b:6,c:10},
  {a:3,b:7,c:11},
  {a:4,b:8,c:12}
];
const mapped = obj.map(({ c, ...rest }) => rest);
console.log(mapped);

如果要包含属性,只需从.map回调中提取它们

var obj = [
  {a:1,b:5,c:9},
  {a:2,b:6,c:10},
  {a:3,b:7,c:11},
  {a:4,b:8,c:12}
];
const mapped = obj.map(({ a, b }) => ({ a, b }));
console.log(mapped);

使用map()

var data = [
  {a:1,b:5,c:9},
  {a:2,b:6,c:10},
  {a:3,b:7,c:11},
  {a:4,b:8,c:12}
];
          
let modified = data.map(obj => ({a: obj.a, b: obj.b}))

console.log(modified);

或者,如果您更喜欢解构:

var data = [
    {a:1,b:5,c:9}, 
    {a:2,b:6,c:10},
    {a:3,b:7,c:11}, 
    {a:4,b:8,c:12}
];
          
let modified = data.map(({ a, b }) => ({a, b}));

console.log(modified);

var obj = [
  {a: 1, b: 5, c: 9},
  {a: 2, b: 6, c: 10},
  {a: 3, b: 7, c: 11},
  {a: 4, b: 8, c: 12}
];

var result = obj.map(e => ({a:e.a , b:e.b}));
console.log(result)

您可以使用返回具有所需属性的自定义对象 map()

var obj = [{a:1,b:5,c:9},
           {a:2,b:6,c:10},
           {a:3,b:7,c:11},
           {a:4,b:8,c:12}
          ];
          
          
let op = obj.map(e => {
   return { a:e.a, b: e.b };
})        

console.log(op);