javascript 如果对象集具有对象属性,则创建数组

r8xiu3jd  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(155)

我有一个动态的响应值,需要存储在redux状态中,
响应由对象数组和名称组成,例如:

{data:[
 {name:"abc",age:"10",id:"10"}
 {name:"abc",age:"15",id:"20"}
 {name:"def",age:"15",id:"20"}
 ]
 name: "abc"
}

所以如果名字是一样的,我需要创建一个数组。
预期:

abc:[
   {name:"abc",age:"10",id:"10"}
   {name:"abc",age:"15",id:"20"}
]

我试过的

data.map(function(o) {
       if(data.name ==o.name)
        return name[o];
 });
iyr7buue

iyr7buue1#

如果你想要一个keyname property的新对象,你可以尝试如下

const response = {
  data: [{
      name: "abc",
      age: "10",
      id: "10"
    },
    {
      name: "abc",
      age: "15",
      id: "20"
    },
    {
      name: "def",
      age: "15",
      id: "20"
    },
  ],
  name: "abc"
}

const createSet = (someData) => {
  let key = someData.name
  let data = someData.data.filter(e => e.name === key)
  return {
    [key]: data
  }
}

console.log(createSet(response))
watbbzwu

watbbzwu2#

您可以使用reducefilter提取重复项:

var data = {
data:[
 {name:"abc",age:"10",id:"10"},
 {name:"abc",age:"15",id:"20"},
 {name:"def",age:"15",id:"20"}
 ],
 name: "abc"
}

const lookup = data.data.reduce((a, e) => {
  a[e.name] = ++a[e.name] || 0;
  return a;
}, {});

console.log(data.data.filter(e => lookup[e.name]));

相关问题