[英]Merge keys in JSON object to return an array of merged keys and the value with Javascript
我想使用 Javascript 將輸入轉換為輸出。 有什么幫助嗎? 輸入也可以有更多的嵌套對象。
const input = {
a: {
b: 22,
c: 'hello',
},
e: 456
}
const output = [
{ 'a.b': 22},
{ 'a.c': 'hello' },
{ 'e': 456 }
];
您可以為此使用reduce
方法創建遞歸函數。
const input = { a: { b: true, c: 'hi', }, d: 123 } function convert(data, prev = '') { return Object.entries(data).reduce((r, [k, v]) => { let key = prev + (prev ? '.' : '') + k; if (typeof v == 'object') { r.push(...convert(v, key)) } else { r.push({ [key]: v }) } return r; }, []) } const result = convert(input) console.log(result)
// 解決問題的最佳和快速方法'
Object.entries(data).reduce((r, [k, v]) => {
使用大 json 時速度較慢。
Object.entries()
const input = { a: { b: 22, c: "hello", d: { f: 10 } }, e: 456 };
function flat(data, key = "", result = []) {
for (let k in data) {
if (typeof data[k] === "object") {
flat(data[k], key + k + ".", result);
} else result.push({ [key + k]: data[k] });
}
return result;
}
console.log(flat(input));
const input = { a: { b: 22, c: "hello", d: { f: 10 } }, e: 456 }; function flat(data, key = "", result = []) { for (let k in data) { if (typeof data[k] === "object") { flat(data[k], key + k + ".", result); } else result.push({ [key + k]: data[k] }); } return result; } console.log(flat(input));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.