javascript - 使用键排除列表展平 json
问题描述
我需要展平 json,但想考虑一个不被处理/添加到列表中的 exclude_keys_array 列表
例如
if I have an exclude_keys_array = ["addresses.metadata", "pageToken"] //只会跳过地址的元数据(第二级跳过)
if I have an exclude_keys_array = ["metadata", "pageToken"] //父json的元数据将被跳过(顶级键跳过)
如何使用排除数组展平 JSON?
var exlusion_list = ["metadata", "meta", "pageToken"];
var crowds = [{
"name": [{
"firstName": "John",
"middleName": "Joseph",
"lastName": "Briggs",
}],
"addresses": [{
"type": "home",
"poBox": "111",
"city": "City1",
"postalCode": "1ER001",
"country": "USA",
}, {
"type": "work",
"poBox": "222",
"city": "City2",
"region": "Region2",
"postalCode": "1ER002",
}],
"photos": [{
"url": "photo.org/person1",
"default": true,
}, {
"url": "imagur.org/person1",
"default": true,
}],
"metadata": [{
"meta-id": "1234",
}],
}, {
"name": [{
"firstName": "Bill",
"lastName": "Thatcher",
}],
"addresses": [{
"type": "home",
"city": "City3",
"region": "Region3",
"postalCode": "1ER003",
"country": "USA",
}, {
"type": "work",
"poBox": "444",
"region": "Region4",
"postalCode": "1ER004",
}, {
"poBox": "555",
"region": "Region5",
"postalCode": "1ER005",
}],
"metadata": [{
"meta-id": "1234",
}],
}];
function flatten(obj, res = {}, key = '') {
let add = (d, s) => key ? key + d + s : s;
if (Array.isArray(obj)) {
obj.forEach((v, n) => flatten(v, res, add(' #', n + 1)));
} else if (typeof obj === 'object') {
Object.entries(obj).forEach(([k, v]) => flatten(v, res, add(': ', k)));
} else {
res[key] = obj;
}
return res;
}
let flats = crowds.map(obj => flatten(obj));
function combineKeys(objs) {
let keys = objs.reduce((k, obj) => k.concat(Object.keys(obj)), []);
return [...new Set(keys)];
}
let keys = combineKeys(flats);
let table = flats.map(f => keys.map(k => f[k] ?? ''));
table.unshift(keys);
console.log({ table });
// document.write(JSON.stringify(table));
.as-console-wrapper { min-height: 100%!important; top: 0; }
// .as-console-wrapper { min-height: 70%!important; bottom: 0; }
解决方案
一个快速的解决方法是过滤下面的键。我认为有一种更有效的方法可以做到这一点,但我没有深入研究代码。
let keys = combineKeys(flats).filter(
key => !exlusion_list.includes(key.split(":")[0].split(" ")[0])
);
推荐阅读
- azure-devops - Azure Devops 中连接到测试套件和测试器的测试结果概述
- c++ - 你能在这段代码中找到回文分区问题的错误吗? https://leetcode.com/problems/palindrome-partitioning/
- google-sheets - Google 表格中的 Google 财务公式有时会导致 N/A 直到刷新
- ios - 从 SwiftUI 的详细视图中删除列表中的最后一项不会弹出详细视图
- phpmyadmin - Phpmyadmin:如何添加默认导出 mysql gzipped 的永久设置
- excel - Excel 输入框中的屏蔽文本
- javascript - 在 excel vba 中查看和访问 DOM Explorer 代码
- c# - C#在dll中调用go函数,并且在.Net Core中运行,go分配的非托管内存会被垃圾收集吗?
- javascript - React hook:如何通过类中的多个按钮调用?
- angular - ngx-mask 不允许货币输入为负值