我是json和javascript的新手,我有以下输入:
var input= {
"careerLevelGroups": [
{
"201801": 58,
"201802": 74,
"careerLevel": "Analyst",
"careerLevels": [
{
"201801": 29,
"201802": 37,
"careerID": "10000100"
},
{
"201801": 29,
"201802": 37,
"careerID": "10000110"
}
]
},
{
"201801": 58,
"201802": 74,
"careerLevel": "Consultant",
"careerLevels": [
{
"201801": 29,
"201802": 37,
"careerID": "10000080"
},
{
"201801": 29,
"201802": 37,
"careerID": "10000090"
}
]
}
]
};
我需要创建这个结果:
var result = {
[
{
"careerLevel": "Analyst",
"careerLevels": [
{
"201801": 29,
"201802": 37,
"careerID": "10000100"
},
{
"201801": 29,
"201802": 37,
"careerID": "10000110"
}
]
},
{
"careerLevel": "Consultant",
"careerLevels": [
{
"201801": 29,
"201802": 37,
"careerID": "10000080"
},
{
"201801": 29,
"201802": 37,
"careerID": "10000090"
}
]
}
]
}
我想我需要做一些像我只需要careerLevel和careerLevels属性的地方(其余全部都应删除)。我尝试了json的循环结构和删除命令,但是没有得到正确的格式。
let clJson = input.careerLevelGroups.forEach(element => {
let keysToDelete = Object.keys(element).filter( // return keys with careerLevel and careerLevels);
// delete keys
});
答案 0 :(得分:1)
使用delete
运算符删除键:
var input = {
"careerLevelGroups": [{
"201801": 58,
"201802": 74,
"careerLevel": "Analyst",
"careerLevels": [{
"201801": 29,
"201802": 37,
"careerID": "10000100"
},
{
"201801": 29,
"201802": 37,
"careerID": "10000110"
}
]
},
{
"201801": 58,
"201802": 74,
"careerLevel": "Consultant",
"careerLevels": [{
"201801": 29,
"201802": 37,
"careerID": "10000080"
},
{
"201801": 29,
"201802": 37,
"careerID": "10000090"
}
]
}
]
};
const result = input.careerLevelGroups;
result.forEach(obj => {
Object.keys(obj).forEach(key => {
if (key !== 'careerLevel' && key !== 'careerLevels') delete obj[key];
})
});
console.log(result);

请注意,这会改变原始对象 - 它不会创建副本。
答案 1 :(得分:1)
最简单的解决方案似乎是使用对象解构的解决方案:
const input= {"careerLevelGroups": [{"201801": 58, "201802": 74, "careerLevel": "Analyst", "careerLevels": [{"201801": 29, "201802": 37, "careerID": "10000100"}, {"201801": 29, "201802": 37, "careerID": "10000110"}]}, {"201801": 58, "201802": 74, "careerLevel": "Consultant", "careerLevels": [{"201801": 29, "201802": 37, "careerID": "10000080"}, {"201801": 29, "201802": 37, "careerID": "10000090"}]}]}
const simplify = ({careerLevel, careerLevels}) => ({careerLevel, careerLevels})
const result = {careerLevelGroups: input.careerLevelGroups.map(simplify)}
console.log(result)

请注意,输出与原始输出稍有不同,这不是合法的语法。
答案 2 :(得分:0)
从对象“obj”中删除项目“xyz”的正确方法是
delete obj["xyz"];