{{1}}
我有一个企业的对象列表(分配了一个ID),每个企业都有自己的国家。
我的问题是通过财产查找金额的最佳方法是什么?例如,如果我想查找法国企业的总数,它将根据代码示例返回3。
答案 0 :(得分:2)
您可以尝试这样的事情:
var Business = {
1: {Country:"France"}
, 2: {Country:"United Kingdom"}
, 3: {Country:"France"}
, 4: {Country:"France"}
};
var businessInFrance = Object.keys(Business)
.map(key => Business[key])
.reduce(function(acc, val){
return val.Country === "France"
? acc+=1
: acc;
},0);
console.log(businessInFrance);
Object.keys(Business)
返回一个数组,其中包含Business
拥有的可枚举map
将我们传递的函数应用于上一步的输出并返回一个新数组。此数组的元素是Business reduce
应用我们为上一步数组的每个元素传递的函数,当Country
属性的值等于“France”时,我们将累加器的值递增1 ,acc
,否则我们将保持不变。然后返回累加器的值。答案 1 :(得分:1)
您的对象存在问题。您可以使用以下内容,但我不得不问为什么不使用数组?
Business = {
01: {Country:"France"},
02: {Country:"United Kingdom"},
03: {Country:"France"},
04: {Country:"France"},
}
const BusinessArray = [
{Country:"France"},
{Country:"United Kingdom"},
{Country:"France"},
{Country:"France"},
]
console.log(
BusinessArray.filter(x => x.Country === 'France').length
)
Business = {
01: {Country:"France"},
02: {Country:"United Kingdom"},
03: {Country:"France"},
04: {Country:"France"},
}
const countriesCount = (country, businesses) =>
Object.keys(businesses)
.filter(x => businesses[x].Country === country)
.length
console.log(
countriesCount('France', Business),
countriesCount('United Kingdom', Business)
)
答案 2 :(得分:1)
您可以使用对象来计算国家/地区。
var business = { 1: { Country: "France" }, 2: { Country: "France" }, 3: { Country: "UnitedKingdom" }, 4: { Country: "France" } },
count = Object.keys(business).reduce(function (r, k) {
var country = business[k].Country;
r[country] = (r[country] || 0) + 1;
return r;
}, Object.create(null));
console.log(count.France);
console.log(count);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)
首先,您的语法不正确,会导致错误。
如果你包含数组中的所有对象,你就不需要这些对象来维护自己的标识符,你可以很容易地做到这一点:
var business = [
{country:"France"},
{country:"United Kingdom"},
{country:"France"},
{country:"France"}
];
console.log("The amount of countries is: " + business.length);
var count = 0;
business.forEach(function(value){
count = (value.country === "France") ? ++count : count;
});
console.log("The amount of times France appears is: " + count);

答案 4 :(得分:0)
Object.keys
返回对象的键。您可以循环键并计算您想要的结果。这是一个例子..
var Business = {
1:{
Country: "France"
},
2:{
Country: "France"
},
3:{
Country: "UnitedKingdom"
},
4:{
Country: "France"
}};
var countByCountry = function(country){
var result = 0;
Object.keys(Business).forEach(function(it){
result += (Business[it].Country === country ? 1 : 0);
console.log(it, country, result);
});
return result;
}
console.log(countByCountry('France'));