在 Javascript 中使用关联数组重组 JSON 数据
Reorganizing JSON data with associative array in Javascript
我有一些类似下面的数据:
let foodsArray = [
{
"food" : "fruit",
"type" : "apple"
} ,
{
"food" : "vegetable",
"type" : "carrot"
} ,
{
"food" : "vegetable",
"type" : "lettuce"
} ,
{
"food" : "fruit",
"type" : "orange"
} ,
]
我想重组如下:
newFoodsArray = [
{
"food" : "fruit",
"type" : ["apple","orange"]
} ,
{
"food" : "vegetable",
"type" : ["carrot", "lettuce"]
} ,
]
迭代这些信息并构建我想要的结果的有效方法是什么?我正在尝试这样的事情,但从语法上讲它不会飞。
for (let i = 0; i < foodsArray; i++)
newFoodsArray[foodsArray[i]["food"]].push(foodsArray[i]["type"]);
您可以使用 reduce 轻松实现此结果。
let foodsArray = [
{
food: "fruit",
type: "apple",
},
{
food: "vegetable",
type: "carrot",
},
{
food: "vegetable",
type: "lettuce",
},
{
food: "fruit",
type: "orange",
},
];
const newFoodsArray = foodsArray.reduce((acc, { food, type }) => {
const isExist = acc.find((el) => el.food === food);
if (isExist) isExist.type.push(type);
else acc.push({ food, type: [type] });
return acc;
}, []);
console.log(newFoodsArray);
我有一些类似下面的数据:
let foodsArray = [
{
"food" : "fruit",
"type" : "apple"
} ,
{
"food" : "vegetable",
"type" : "carrot"
} ,
{
"food" : "vegetable",
"type" : "lettuce"
} ,
{
"food" : "fruit",
"type" : "orange"
} ,
]
我想重组如下:
newFoodsArray = [
{
"food" : "fruit",
"type" : ["apple","orange"]
} ,
{
"food" : "vegetable",
"type" : ["carrot", "lettuce"]
} ,
]
迭代这些信息并构建我想要的结果的有效方法是什么?我正在尝试这样的事情,但从语法上讲它不会飞。
for (let i = 0; i < foodsArray; i++)
newFoodsArray[foodsArray[i]["food"]].push(foodsArray[i]["type"]);
您可以使用 reduce 轻松实现此结果。
let foodsArray = [
{
food: "fruit",
type: "apple",
},
{
food: "vegetable",
type: "carrot",
},
{
food: "vegetable",
type: "lettuce",
},
{
food: "fruit",
type: "orange",
},
];
const newFoodsArray = foodsArray.reduce((acc, { food, type }) => {
const isExist = acc.find((el) => el.food === food);
if (isExist) isExist.type.push(type);
else acc.push({ food, type: [type] });
return acc;
}, []);
console.log(newFoodsArray);