如何在没有重复语句的情况下排列Array的JSON数据



首先,很抱歉我的英语不好,谢谢你点击这个问题。

我有一个像这样的原始数据

苹果红、香蕉黄、奇异果绿、葡萄紫、苹果酸、香蕉甜

我想用这些原始数据制作JSON数据,比如

[
{
apple : {
color : "red",
tastes : "sour"
}
},
{
banana : {
color : "yellow",
tastes : "sweet"
}
}, ...
]

所以我用.split("-"(修剪了数据,并在空数组上添加了带有重复语句的JSON元素(用表示(。

但我的结果就像

[
{
apple : {
color : "red"
}
},
{
apple : {
tastes : "sour"
}
},
{
banana : {
color : "yellow"
}
}, 
{
banana : {
tastes : "sweet"
}
}, 
...
]

只有很少的颜色(红、黄、绿…(属性和味道(酸、甜、辣…件是这样的,也许我可以处理

但我的问题是Array元素的check键有太多重复的语句。

我必须检查所有数组元素中是否存在"apple",然后才能添加其他属性。

我该如何解决这个问题?

您应该使用映射来对水果进行分组,并检查该值是否与特定属性相对应,并将该值设置为正确的属性,如以下示例所示:

function arrangeFruits(str) {
const map = {};
const colors = ['red', 'yellow', 'green', 'purple'];
const tastes = ['sour', 'sweet'];
const parts = str.split(',');
parts.forEach((item) => {
const [index, attr] = item.split('-');
if (!map[index]) {
map[index] = {};
}
if (colors.includes(attr)) {
map[index].color = attr;
} else if (tastes.includes(attr)) {
map[index].tastes = attr;
}
});
const fruits = [];
for (const item in map) {
const fruit = {};
fruit[item] = map[item];
fruits.push(fruit);
}
return fruits;
}
const result = arrangeFruits(
'apple-red,banana-yellow,kiwi-green,grape-purple,apple-sour,banana-sweet'
);
console.log(JSON.stringify(result));

假设您已经拥有对象

$currentObject = {
apple : {
color : "red"
}
};
$newObject  = {
apple : {
tastes : "sour"
}
};

您可以根据此处的文档尝试使用lodash合并:https://lodash.com/docs/4.17.15#merge将您的对象深度合并为一个。

_.merge($currentObject, $newObject);

相关内容

最新更新