我是 JS 新手,試圖弄清楚如何遍歷 json 陣列并只回傳元素的子集。具體來說,我想知道如何從附加代碼片段中的 Mock 資料中只回傳“first_name”和“last_name” 。看起來應該很簡單,但我正在摸不著頭腦。
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
uj5u.com熱心網友回復:
使用元素名稱
people.forEach(person => {
console.log(JSON.stringify(person) "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
產生這個輸出:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}
Lenore Foister
uj5u.com熱心網友回復:
您可以通過使用地圖功能來實作這一點。
map 允許您遍歷陣列中的每個專案并為每次迭代回傳一個新值,同時回傳一個新陣列,因此對于您的情況:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
在這里,您將獲得一個新陣列,其中包含您需要的屬性。
uj5u.com熱心網友回復:
有許多方法可以實作此輸出。最常用的方法之一是使用map()es6。
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
uj5u.com熱心網友回復:
您可以嘗試 ES6 的物件解構賦值來實作需求。
作業演示:
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name ' ' last_name);
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426817.html
