Reputation: 39
var json = [{
"city": "California",
"name": "Joe",
"age": 17
}, {
"city": "California",
"name": "Bob",
"age": 17
}, {
"city": "California",
"name": "Bob",
"age": 35
}, {
"city": "Texas",
"name": "Bob",
"age": 35
}, {
"city": "Florida",
"name": "Bob",
"age": 35
}
];
I just to no of occurence based on city value i.e output as below.
updatedjson=[{"name":"California","count":3},{"name":"Texas","count":1},{"name":"Florida","count":1}]
using any approah using lodash or javascript
Upvotes: 1
Views: 678
Reputation: 33466
Using Lodash, that would be:
const updatedJson = _(json)
.countBy('city')
.map((count, name) => ({ name, count }))
.value();
const json = [{"city":"California","name":"Joe","age":17},{"city":"California","name":"Bob","age":17},{"city":"California","name":"Bob","age":35},{"city":"Texas","name":"Bob","age":35},{"city":"Florida","name":"Bob","age":35}];
const updatedJson = _(json)
.countBy('city')
.map((count, name) => ({ name, count }))
.value();
console.log(JSON.stringify(updatedJson));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
Upvotes: 1
Reputation: 1201
Here is how you will get it:
updatedJson = [
{
name: "California",
count: (_.filter(json, item => item.city === "California").length)
}
]
Upvotes: 0
Reputation: 386560
You could collect the count with Map
and render the result with the wanted properties.
var data = [{ city: "California", name: "Joe", age: 17 }, { city: "California", name: "Bob", age: 17 }, { city: "California", name: "Bob", age: 35 }, { city: "Texas", name: "Bob", age: 35 }, { city: "Florida", name: "Bob", age: 35 }],
result = Array.from(
data.reduce((m, { city }) => m.set(city, (m.get(city) || 0) + 1), new Map),
([name, count]) => ({ name, count })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 1369
var json = [{
"city": "California",
"name": "Joe",
"age": 17
}, {
"city": "California",
"name": "Bob",
"age": 17
}, {
"city": "California",
"name": "Bob",
"age": 35
}, {
"city": "Texas",
"name": "Bob",
"age": 35
}, {
"city": "Florida",
"name": "Bob",
"age": 35
}
];
var hash = {}; // will be used for lookup of index of city in updated_json array.
var updated_json = [];
json.forEach(function(item,index){
// if city exists in hash then retrive its position from hash.
if(item.city in hash){
updated_json[hash[item.city]].count++;
}
else{
hash[item.city] = updated_json.length; // store position
updated_json.push({"name":item.city,"count":1});
}
});
console.log(updated_json);
Upvotes: 0