从服务呼叫中,我收到类似的JSON数据,如下所示:
myArray: any = [
{item: 'Jelly Beans', areaCode: 321, Company: "Bob's Candy"},
{item: 'Skittles', areaCode: 444, Company: "Jim's Candy"},
{item: 'Snickers', areaCode: 321, Company: "Bob's Candy"},
{item: 'M&Ms', areaCode: 444, Company: "Jim's Candy"},
{item: 'Gummy Bears', areaCode: 123, Company: "Sally's Candy"}];
我需要根据areaCode将其动态拆分为多个对象数组。
或基于areaCode动态创建一个新对象。
this.myArray= this.data.map(item => item.areaCode)
.filter((value, index, self) => self.indexOf(value) === index);
我考虑过使用map函数并根据areaCode对其进行过滤,然后也许使用基于areaCode的数组创建一个新对象。我似乎无法全神贯注于此过程。如果有人可以提供一些建议,我将不胜感激。
答案 0 :(得分:1)
您期望输出这样的内容
{
"123":[{"item":"Gummy Bears","areaCode":123,"Company":"Sally's Candy"}],
"321":[{"item":"Jelly Beans","areaCode":321,"Company":"Bob's Candy"},
{"item":"Snickers","areaCode":321,"Company":"Bob's Candy"}],
"444":[{"item":"Skittles","areaCode":444,"Company":"Jim's Candy"},
{"item":"M&Ms","areaCode":444,"Company":"Jim's Candy"}]
}
然后您可以减少实现目标
const output = myArray.reduce((res,v) => {
if(!res[v.areaCode]) {
res[v.areaCode] = [v]
} else {
res[v.areaCode].push(v)
}
return res
},{} )
答案 1 :(得分:1)
您可以改为使用 arrayData : [
0: {
is_required: true
name: "vmvdnksl"
}
1: {
is_required: true
name: "dsvnlk"
}
]
将数组转换为对象,然后使用.reduce
从reduces对象中获取唯一对象的数组,如下所示:
Object.values()