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
}
];
我只是根据城市价值出现,即输出如下。
updatedjson=[{"name":"California","count":3},{"name":"Texas","count":1},{"name":"Florida","count":1}]
使用lodash或javascript使用任何appsah
答案 0 :(得分:1)
使用Lodash,即:
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>
&#13;
答案 1 :(得分:0)
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);
答案 2 :(得分:0)
以下是您将如何获得它:
updatedJson = [
{
name: "California",
count: (_.filter(json, item => item.city === "California").length)
}
]
答案 3 :(得分:0)
您可以使用Map
收集计数,并使用所需的属性呈现结果。
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;