我正在尝试解析下面的 JSON(格式),将其展平并获取所需的键/值(输出),如下所述。我正在尝试找出最好的方法来做到这一点。
我需要获取displayName及其对应的父级
例如: 特征:taxoFeatures
输入:
{
"Shop": {
"subFilter": [
{
"taxoFeatures": {
"displayName": "Features"
}
},
{
"color_base": {
"displayName": "Colour"
}
}
],
"displayName": "Shopping"
},
"Support": {
"subFilter": [
{
"contentType": {
"displayName": "Content"
}
}
],
"displayName": "Support documents"
}
}
预期输出:
{
"Shopping": "Shop",
"Features":"taxoFeatures",
"Colour":"color_base",
"Content":"contentType",
"Support documents":"Support"
}
我正在考虑循环遍历 JSON 并找到键并添加相应的键和 displayName 值(然后循环遍历每个子数组并存储这些值)。还有其他想法吗?
let customName = {};
for (const key in filter) {
if (filter.hasOwnProperty(key)) {
const value = filter[key];
if (isNotEmpty(value.displayName)) {
customName[value.displayName] = key;
}
}
}
最佳答案
您可以使用此递归函数,该函数使用 reduce
和 Object.assign
构建结果对象:
function transform(filter) {
return Object.keys(filter).reduce( (acc, key) => {
const value = filter[key];
if (Object(value) === value) { // it's an object
if ('displayName' in value) {
acc[value.displayName] = key;
}
Object.assign(acc, transform(value)); // recurse
}
return acc;
}, {});
}
// Sample input
const filter = {
"Shop": {
"subFilter": [
{
"taxoFeatures": {
"displayName": "Features"
}
},
{
"color_base": {
"displayName": "Colour"
}
}
],
"displayName": "Shopping"
},
"Support": {
"subFilter": [
{
"contentType": {
"displayName": "Content"
}
}
],
"displayName": "Support documents"
}
}
console.log(transform(filter));
关于javascript - 在javascript中解析Json并获取键/值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42936545/