英文:
How to add element and remove element from array through javascript
问题
let objArr = [
{ "name": "mark", "height": "tall", "hairColor": "black" },
{ "name": "ben", "height": "medium", "color": "fair" },
{ "name": "neil", "height": "small", "color": "dark" }
];
addmoreObject = {"gender": "male", "age": 33};
const res = objArr.map(({ hairColor, color, ...r }) => r);
console.log("RES", res);
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let objArr = [
{ "name" : "mark", "height" : "tall", "hairColor": "black"},
{ "name" : "ben", "height" : "medium", "color": "fair"},
{ "name" : "neil", "height" : "small", "color": "dark"}
];
addmoreObject = {"gender": "male", "age": 33};
const res = objArr.map(({ hairColor, color, addmoreObject ...r }) => r);
console.log("RES", res)
<!-- end snippet -->
I wanted to remove color and hairColor from object and wanted to add more element like gender, age etc. how can I make it in correct manner please guide
https://jsfiddle.net/v0yLu8m2/
答案1
得分: 2
你很接近:
// 更改为
const res = objArr.map(({ hairColor, color, ...rest }) => {
return {
...rest,
...addmoreObject,
};
});
英文:
You're very close:
// Change
const res = objArr.map(({ hairColor, color, addmoreObject ...r }) => r);
// To
const res = objArr.map(({ hairColor, color, ...rest }) => {
return {
...rest,
...addmoreObject,
};
});
答案2
得分: 0
let objArr = [
{ "name" : "mark", "height" : "tall", "hairColor": "black"},
{ "name" : "ben", "height" : "medium", "color": "fair"},
{ "name" : "neil", "height" : "small", "color": "dark"}
];
let addmoreObject = {"gender": "male", "age": 33};
let newArr = objArr.map(({ hairColor, color, ...rest }) => ({ ...rest, ...addmoreObject }));
console.log(newArr);
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let objArr = [
{ "name" : "mark", "height" : "tall", "hairColor": "black"},
{ "name" : "ben", "height" : "medium", "color": "fair"},
{ "name" : "neil", "height" : "small", "color": "dark"}
];
let addmoreObject = {"gender": "male", "age": 33};
let newArr = objArr.map(({ hairColor, color, ...rest }) => ({ ...rest, ...addmoreObject }));
console.log(newArr);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论