[英]How to extract Values of particular key in an object array without iterating over the array?
假設我有一個像下面這樣的對象數組調用影片 。
movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}]
無論如何,我可以從每個對象中提取特定鍵的值嗎? 像這樣的標題數組。
titles = ['Black Panther','Avengers','Justice League','Infinity War','Spider Man']
目前,我正在使用map
功能。 還有其他方法可以實現此目標而無需遍歷每個對象。 可以使用ES6的剩余/擴展功能來實現嗎?
不,如果不循環遍歷數組,則無法執行此操作。 不,休息/散布也無濟於事。
您已經說過您正在使用map
,這可能是最簡單的方法:
titles = movies.map(e => e.title);
const movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}]; const titles = movies.map(e => e.title); console.log(JSON.stringify(titles));
或具有破壞性:
titles = movies.map(({title}) => title);
const movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}]; const titles = movies.map(({title}) => title); console.log(JSON.stringify(titles));
您也可以使用for-of
:
titles = [];
for (const {title} of movies) {
titles.push(title);
}
const movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}]; const titles = []; for (const {title} of movies) { titles.push(title); } console.log(JSON.stringify(titles));
不,傳播無法做到這一點。 您可以將map與參數解構結合起來:
list.map(({ title }) => title)
或者,您可以使用lodash/map
,它是您的用例的簡寫形式:
import { map } from 'lodash'
map(list, 'title')
使用lodash/fp
,您甚至可以在其他地方重用您的功能:D
import { map } from 'lodash/fp'
const getTitles = map('title')
getTitles(list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.