Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

json - Pivot or Transforming JavaScript object

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": "Dan",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]

How can I transform or pivot to generate the following object?

[
 { "47201": [
              {"name": "Dan", "city": "Columbus"},
              {"name": "Jen", "city": "Columbus"},
             ],
    "count": "2"
  },
  { "33602": [
              {"name": "Mark", "city": "Tampa"}
             ],
    "count": "1"
  }
 ]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...