![](/img/trans.png)
[英]How to check if an array of objects where I push into objects has a specific key value from another array of objects
[英]How can I push a prop and its value to objects that don't have that specific property knowing that these objects are in an array of objects
我想要實現的是:-
循環遍歷peopleData
數組,添加一個名為'age'
的prop
,如果其中一個對象(數組元素)沒有鍵“age”,則為其賦值'-'
”
const peopleData = [ { name: "Ann", age: 15, email: "ann@test.com", birthMonth: "Jan" }, { name: "Bob", age: 19, email: "bob@test.com", birthMonth: "Mar" }, { name: "Cam", age: 18, email: "cam@test.com", birthMonth: "Feb" }, { name: "Dan" }, { name: "Steve", birthMonth: "Jun" }, { name: "Tyson", age: 20, birthMonth: "Dec" }, ];
我試圖做的事情並沒有奏效
const addAgeObj = {age: '-'}
const myArr = peopleData.map(personData=> {
if(!personData.age) {
peopleData.push(addAgeObj);
console.log(peopleData);
}
});
peopleData.push
是錯誤的。 您需要更新對象,而不是向數組中添加新對象。
const peopleData = [ { name: "Ann", age: 15, email: "ann@test.com", birthMonth: "Jan" }, { name: "Bob", age: 19, email: "bob@test.com", birthMonth: "Mar" }, { name: "Cam", age: 18, email: "cam@test.com", birthMonth: "Feb" }, { name: "Dan" }, { name: "Steve", birthMonth: "Jun" }, { name: "Tyson", age: 20, birthMonth: "Dec" }, ]; const myArr = peopleData.map(personData=> { return {...personData, age: personData.age || '-'} }); console.log(myArr);
const addAgeObj = {age: '-'} const peopleData = [ { name: "Ann", age: 15, email: "ann@test.com", birthMonth: "Jan" }, { name: "Bob", age: 19, email: "bob@test.com", birthMonth: "Mar" }, { name: "Cam", age: 18, email: "cam@test.com", birthMonth: "Feb" }, { name: "Dan" }, { name: "Steve", birthMonth: "Jun" }, { name: "Tyson", age: 20, birthMonth: "Dec" }, ]; const myArr = peopleData.map(personData=> { /* if(!personData.age) { peopleData.push(addAgeObj); console.log(peopleData); }*/ if(!Object.keys(personData).includes("age")) personData={...personData,addAgeObj} return personData }); console.log(myArr)
嘗試這個
peopleData.push 所做的是添加新對象並覆蓋現有對象。所以這是錯誤的,這不是你想要的。所以試試這個。
const peopleData = [
{ name: "Ann", age: 15, email: "ann@test.com", birthMonth: "Jan" },
{ name: "Bob", age: 19, email: "bob@test.com", birthMonth: "Mar" },
{ name: "Cam", age: 18, email: "cam@test.com", birthMonth: "Feb" },
{ name: "Dan" },
{ name: "Steve", birthMonth: "Jun" },
{ name: "Tyson", age: 20, birthMonth: "Dec" },
];
const myArr = peopleData.map(personData=> {
if(!personData.age) {
let newobj={...personData,age:"-"};
return newobj;
}
else{
return personData;
}
});
console.log(myArr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.