[英]How to convert an array of objects back to one object
我得到了一組具有以下結構的對象:
const cars = {
ford: {
entries: ['ford 150']
},
chrysler: {
entries: ['Voyager']
},
honda: {
entries: []
},
toyota: {
entries: ['sienna']
},
mercedes: {
entries: []
},
}
為了讓用戶能夠重新排列汽車的順序,我需要過濾掉條目為零的汽車品牌,所以我這樣做:
const filteredCars = Object.values(cars).filter(removeCarsWithNoEntries)
function removeCarsWithNoEntries(e) {
if (e.entries[0]) return e.entries
}
然后,一旦順序重新排列,我必須將 object 轉換回其原始形式,但順序重新排列,意思是這樣的:
cars = {
toyota: {
entries: ['sienna']
},
chrysler: {
entries: ['Voyager']
},
ford: {
entries: ['ford 150']
},
honda: {
entries: []
},
mercedes: {
entries: []
},
}
我已經閱讀了array.reduce
和Object.assign
但到目前為止我嘗試過的東西不起作用。
如何將對象數組轉換回具有 0 個條目的原始汽車品牌的單個 object? 謝謝。
You can convert the object to entries via Object.entries()
, and then filter/sort by the value (the 2nd item in the pair), and convert back to an object using Object.fromEntries()
:
const cars = {"ford":{"entries":["ford 150"]},"chrysler":{"entries":["Voyager"]},"honda":{"entries":[]},"toyota":{"entries":["sienna"]},"mercedes":{"entries":[]}} const sorted = Object.fromEntries( Object.entries(cars).sort(([, { entries: a }], [, { entries: b }]) => b.length - a.length) ) const filtered = Object.fromEntries( Object.entries(cars).filter(([, v]) => v.entries.length) ) console.log({ sorted, filtered })
檢查您的代碼... filter
方法不起作用,因為返回一個數組...您是否需要使用length
屬性來檢查是否有值,否則它將始終為true
const cars = { ford: { entries: ['ford 150'] }, chrysler: { entries: ['Voyager'] }, honda: { entries: [] }, toyota: { entries: ['sienna'] }, mercedes: { entries: [] }, } filtered = {} Object.keys(cars).forEach(removeCarsWithNoEntries) function removeCarsWithNoEntries(brand) { if(.cars[brand].entries.length) return filtered[brand] = cars[brand] } console.log(filtered)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.