简体   繁体   English

如何将一组对象转换回一个 object

[英]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:然后,一旦顺序重新排列,我必须将 object 转换回其原始形式,但顺序重新排列,意思是这样的:

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.我已经阅读了array.reduceObject.assign但到目前为止我尝试过的东西不起作用。

How can I convert the array of objects back to one single object with the original car brands that had 0 entries?如何将对象数组转换回具有 0 个条目的原始汽车品牌的单个 object? 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() : 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检查您的代码... 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.

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