简体   繁体   中英

How to convert an array of objects back to one object

I got an array of objects that has the following structure:

const cars = {
  ford: {
    entries: ['ford 150']
  },
  chrysler: {
    entries: ['Voyager']
  },
  honda: {
    entries: []
  },
  toyota: {
    entries: ['sienna']
  },
  mercedes: {
    entries: []
  },
}

For the user to be able to rearrange the order of the cars, I need to filter out the car brands that have zero entries, so I do this:

const filteredCars = Object.values(cars).filter(removeCarsWithNoEntries)

function removeCarsWithNoEntries(e) {
  if (e.entries[0]) return e.entries
}

Then, once the order is rearranged, I have to convert the object back to its original form, but with the order rearranged, meaning something like this:

cars = {
   toyota: {
    entries: ['sienna']
  },
  chrysler: {
    entries: ['Voyager']
  },
  ford: {
    entries: ['ford 150']
  },
  honda: {
    entries: []
  },
  mercedes: {
    entries: []
  },
}

I've read upon array.reduce and Object.assign but so far the things I have tried do not work.

How can I convert the array of objects back to one single object with the original car brands that had 0 entries? Thanks.

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 })

Checking your code... the filter method doesn't works because return an array... do you need use length property to check if has values, otherwise it will always be 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM