[英]How do I shift child nodes of JSON to parent in JavaScript
I have a JSON object which is我有一个 JSON object 这是
let data = {
"key1" : 1,
"key2" : 2,
"subKeys":{
"subKey1" : 3,
"subKey2" : 4
}
}
I want my resultant JSON like this structure:我希望我的结果 JSON 像这样的结构:
let resultantData = {
"key1":1,
"key2":2,
"subKey1":3,
"subKey2":4
}
How can I achieve this goal我怎样才能实现这个目标
This should do it for you:这应该为你做:
Object.entries(data).forEach(([key, val]) => {
if (typeof val === 'object' && !Array.isArray(val)) {
// if the item is an object and not an array, copy over the values.
Object.entries(val).forEach(([subKey, subVal]) => {
data[subKey] = data[subVal];
});
// delete original child object.
delete data[key];
}
})
Assuming you're using a fairly recent version of a JavaScript runtime due to the 'let' statement.由于“let”语句,假设您使用的是 JavaScript 运行时的相当新版本。
There are a couple of ways of doing this but the most direct is to merge the two hashes and then delete the key 'subKeys'.有几种方法可以做到这一点,但最直接的方法是合并两个哈希,然后删除键“subKeys”。
I found this in another SO article .我在另一篇 SO文章中发现了这一点。 Please upvote if it helps.
如果有帮助请点赞。
let data = {
"key1" : 1,
"key2" : 2,
"subKeys":{
"subKey1" : 3,
"subKey2" : 4
}
};
let merged = { ...data, ...data['subKeys']};
delete merged['subKeys']
console.log(merged);
To make this method more dynamic, you can use a recursive approach to flatten deeply nested objects with multiple levels.要使此方法更具动态性,您可以使用递归方法来展平具有多个级别的深层嵌套对象。 You can do this by taking the object's entries, and mapping them until no
[key, value]
pair array has a value
which is an object by recursively mapping the object value
's entires.您可以通过获取对象的条目并映射它们直到没有
[key, value]
对数组具有 object 的value
,方法是递归地映射 object value
的全部值。 To show this, I've added an additional nested object within your subKeys
object called subsubKeys
:为了展示这一点,我在您的子键 object 中添加了一个额外的嵌套
subKeys
,称为subsubKeys
:
const data = { "key1": 1, "key2": 2, "subKeys":{ "subKey1": 3, "subKey2": 4, "subsubKeys": {"subsubKey1": 100}, "subKey3": 5 } }; const getEntries = obj => Object.entries(obj).flatMap( ([key, val]) => Object(val) === val? getEntries(val): [[key, val]] ); const flattenObj = obj => Object.fromEntries(getEntries(obj)); console.log(flattenObj(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.