Pivot or Transforming JavaScript object

后端 未结 2 1289
忘掉有多难
忘掉有多难 2021-01-17 07:51

I have the following JavaScript object. I need to generate a new object from the given object. What is the approach I should take in JavaScript?

[
 {\"name\"         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 08:28

    I don't know why you want the .count property, when that can be accessed via the array's .length property, but anyway:

    const input = [
      {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
      {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
      {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
    ]
    
    const working = input.reduce((acc, {ZIP, name, city}) => {
      (acc[ZIP] || (acc[ZIP] = [])).push({name, city})
      return acc
    }, {})
    
    const output = Object.keys(working)
      .map(k => ({[k]: working[k], count: working[k].length}))
    
    console.log(output)

    Further reading:

    • Array .reduce()
    • Array .map()
    • Object.keys()
    • Unpacking fields from objects passed as function parameters
    • Computed property names

提交回复
热议问题