gpt4 book ai didi

javascript - 如何深度删除对象中的键?

转载 作者:行者123 更新时间:2023-11-29 16:04:05 25 4
gpt4 key购买 nike

我有一个从 API 返回的这个 json 对象,它有一些怪癖,我想对其进行规范化,以便我可以对每个响应处理相同的输入。这意味着摆脱多余的键:

响应:

{
_links: {...},
_embedded: {
foo: [
{
id: 2,
_embedded: {
bar: []
}
}
]
}
}

所以我想删除所有 _embedded 键并将其展平,如下所示:

{
_links: {...},
foo: [
{
id: 2,
bar: []
}
]
}

这就是我目前所拥有的,但它只适用于顶层,我认为它不适用于数组。

_.reduce(temp1, function(accumulator, value, key) {
if (key === '_embedded') {
return _.merge(accumulator, value);
}
return accumulator[key] = value;
}, {})

最佳答案

一旦你看到一个以 _ 开头的键,就对你的所有键进行递归循环只需将其删除即可。

代码:

var
// The keys we want to remove from the Object
KEYS_TO_REMOVE = ['_embedded'],

// The data which we will use
data = {
_links: {'a': 1},
_embedded: {
foo: [
{
id: 2,
_embedded: {
bar: []
}
},
{
id: 3,
_embedded: {
bar: [
{
id: 4,
_embedded: {
bar: []
}
}
]
}
}
]
}
};

/**
* Flatten the given object and remove the desired keys if needed
* @param obj
*/
function flattenObject(obj, flattenObj) {

var key;

// Check to see if we have flatten obj or not
flattenObj = flattenObj || {};

// Loop over all the object keys and process them
for (key in obj) {

// Check that we are running on the object key
if (obj.hasOwnProperty(key)) {

// Check to see if the current key is in the "black" list or not
if (KEYS_TO_REMOVE.indexOf(key) === -1) {

// Process the inner object without this key
flattenObj[key] = flattenObject(obj[key], flattenObj[key]);
} else {
flattenObject(obj[key], flattenObj);
}

}
}

return flattenObj;


}

console.log(flattenObject(data));

关于javascript - 如何深度删除对象中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35877467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com