我有这个数组:
my_json = [
{
"DontNeed":"Remove",
"year":"2015",
"Some name": "some value"
},
{
"DontNeed":"Remove",
"year":"2016",
"Some name": "another value"
},
];
我想要这样的JSON:
new_json = [
{
"year":"2015",
"Some name": "some value"
},
{
"year":"2016",
"Some name": "another value"
},
];
有没有办法做到这一点?一个已知的功能?
答案 0 :(得分:0)
您可以使用delete运算符从对象中删除已知键(在这种情况下为属性)。结合map
函数,您可以快速从所有条目中删除该属性。
var my_json = [
{
"DontNeed":"Remove",
"year":"2015",
"Some name": "some value"
},
{
"DontNeed":"Remove",
"year":"2016",
"Some name": "another value"
},
];
var expected = my_json.map(j => {
delete j['DontNeed']
return j;
});
console.log(expected);
正如@Mark Meyer在评论中提到的,这也会从my_json
中删除prop / value。如果您想保留原件,请参阅他的答案。万一该答案由于任何原因而消失:new_json = my_json.map(({DontNeed, ...rest}) => rest);
。但是,如果要接受此答案,则应接受他的答案。
答案 1 :(得分:0)
您已用javascript
标记了该问题,所以我假设您正在寻找针对此问题的JavaScript解决方案。
假设您的JSON位于某种对象中(我认为这是my_json
),则可以简单地执行以下操作:
for (var x in my_json) {
delete x['DontNeed'];
}
答案 2 :(得分:0)
不要再为拥有更多属性而烦恼,保持原状。
如果您确实做不到,请使用Array.map
函数,如下所示:
my_json = [
{ "DontNeed":"Remove", "year":"2015", "Some name": "some value" },
{ "DontNeed":"Remove", "year":"2016", "Some name": "another value" }
];
new_json = my_json.map(x => ({
year: x.year,
'Some name': x['Some name']
}));
console.log(new_json);
希望有帮助。
答案 3 :(得分:0)
您可以解构不需要的一个或多个属性,并使用map()
创建一个新数组:
let my_json = [
{"DontNeed":"Remove","year":"2015","Some name": "some value"},
{"DontNeed":"Remove","year":"2016","Some name": "another value"}
];
let new_json = my_json.map(({DontNeed, ...rest}) => rest)
console.log(new_json)