我有一個這樣的物件:
var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]}
我試圖過濾物件以僅顯示年齡在 35 歲以上的作者。這是我所期望的:
var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}]}
但是,由于陣列位于非陣列物件中,所以我還不能使用 filter()。如何解決這個問題?
uj5u.com熱心網友回復:
如果您有多個變數保持不變,這將很有幫助:
var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]}
obj = {
...obj,
author: obj.author.filter( x => x.age >= 35)
}
console.log(obj)
盡管我建議保留原始obj
物件并為過濾后的 obj 創建一個新物件:
var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]}
const above35 = {
...obj,
author: obj.author.filter( x => x.age >= 35)
}
console.log(obj,"and",above35)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
uj5u.com熱心網友回復:
obj.author = obj.author.filter(checkAge); // this will return an array with 1 object.
function checkAge(author) {
return author.age >= 35;
}
uj5u.com熱心網友回復:
一種簡單的方法是這樣的:
var obj = {
name: "Lesson I",
author: [
{ name: "Thomas", age: "40" },
{ name: "Richard", age: "33" },
],
};
const result = obj.author.filter((ob) => ob.age > 35);
obj.author = result;
console.log(obj);
uj5u.com熱心網友回復:
filter()
一種方法...用原始物件的每個鍵/值宣告一個新物件,但author
值:
let obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]};
let obj_old_authors = {
name: obj.name,
author: obj.author.filter(author => 35 < author.age)
};
console.log(obj_old_authors);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517198.html