我正在学习ES6和对象,并且想知道如何摆脱这种对象数组中的一个键值对:
[
{ "name" : "mark", "height" : "tall", "theId" : "1", "nat" : "uk"},
{ "name" : "ben", "height" : "medium", "theId" : "2", "nat" : "uk"},
{ "name" : "neil", "height" : "small", "theId" : "3", "nat" : "uk" }
]
结果应为:
[
{ "name" : "mark", "height" : "tall", "nat" : "uk"},
{ "name" : "ben", "height" : "medium", "nat" : "uk"},
{ "name" : "neil", "height" : "small", "nat" : "uk" }
]
我创建了一个forEach函数,并尝试将每个结果推送到一个新数组中,但是现在没有对象。
如何解决?还是有更好的方法使用ES6 / ES7语法做到这一点?谢谢你的帮助。代码和codePen URL如下:
Codepen:https://codepen.io/anon/pen/bPYQyb
let objArr = [
{ "name" : "mark", "height" : "tall", "theId" : "1", "nat" : "uk"},
{ "name" : "ben", "height" : "medium", "theId" : "2", "nat" : "uk"},
{ "name" : "neil", "height" : "small", "theId" : "3", "nat" : "uk" }
],
arr = [];
objArr.forEach(function(obj) {
for (let column in obj) {
let currArr = [];
if (isNaN(obj[column])) {
console.log('true');
currArr.push(obj[column]);
}
arr.push(currArr);
}
});
console.log(arr);
答案 0 :(得分:4)
objArr.forEach(a => delete a.theId);
用于删除运算符的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
答案 1 :(得分:2)
只需删除密钥:
let objArr = [
{ "name" : "mark", "height" : "tall", "theId" : "1", "nat" : "uk"},
{ "name" : "ben", "height" : "medium", "theId" : "2", "nat" : "uk"},
{ "name" : "neil", "height" : "small", "theId" : "3", "nat" : "uk" }
];
objArr.forEach(function(obj) {
delete obj.theId;
});
console.log(objArr);
答案 2 :(得分:2)
如果要就地修改当前对象,则可以遍历数组中的对象并使用delete <name_of_key>;
语句(doc here)。即使对象中不存在密钥,也可以安全使用。
所以你可以做
for (let obj of objArr) {
delete obj.theId;
}
或功能方式
objArr.forEach(obj => delete obj.theId);
答案 3 :(得分:1)
如果使用immutability is important,则一种方法是将.map()
中的每个项目objArray
转换为新的arr
数组,在该数组中,您可以在地图回调期间过滤掉键为"theId"
的条目。
要过滤掉"theId"
键,通过item
循环迭代当前正在映射的for(.. in ..)
的键,请检查key
是否不是{{1} },如果是这样,请将其及其值(即"thisId"
)添加到新对象中:
item[key]
答案 4 :(得分:1)
只需将destructuring和spreading与map
一起使用,并隐式返回arrow function:
let objArr = [{"name":"mark","height":"tall","theId":"1","nat":"uk"},{"name":"ben","height":"medium","theId":"2","nat":"uk"},{"name":"neil","height":"small","theId":"3","nat":"uk"}];
const res = objArr.map(({ theId, ...r }) => r);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 5 :(得分:1)
尝试一下:
var list = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("Value", 0),
new KeyValuePair<string, string>("Value1", 79),