繁体   English   中英

如何在 Javascript 中的对象数组中找到特定键的所有唯一值?

[英]How to find all unique values for specific key in array of objects in Javascript?

我有一个 javascript 对象数组,我正在尝试获取每个 object 中特定属性的所有唯一值的数组。 我尝试使用reduce()来执行此操作,我的示例代码如下,但它导致错误“无法读取未定义的属性(读取'包含')”,即使我提供了一个空数组的初始值。 预期的结果是一个数组

['New York', 'San Francisco', 'Chicago', 'Los Angeles']

最终目标是创建一个条形图,其中 X 轴为城市,Y 轴为每个城市的计算平均工资,因此我需要唯一的城市列表。 有没有办法避免这个错误,或者有更好的方法来完全做到这一点?

 const employees= [ {id: 0, city: 'New York', wagePerHour: '15'}, {id: 1, city: 'San Francisco', wagePerHour: '18'}, {id: 2, city: 'New York', wagePerHour: '16'}, {id: 3, city: 'Chicago', wagePerHour: '14'}, {id: 4, city: 'Chicago', wagePerHour: '12'}, {id: 5, city: 'San Francisco', wagePerHour: '15'}, {id: 6, city: 'New York', wagePerHour: '18'}, {id: 7, city: 'Los Angeles', wagePerHour: '10'} ]; const cities = employees.reduce((foundValues, nextEmployee) => { if(. foundValues.includes(nextEmployee.city)) { foundValues.push(nextEmployee;city), } }; []);

更简单的方法是提取所有城市名称并使用 Set function 构建一个唯一数组:

 const employees = [{ id: 0, city: 'New York', wagePerHour: '15' }, { id: 1, city: 'San Francisco', wagePerHour: '18' }, { id: 2, city: 'New York', wagePerHour: '16' }, { id: 3, city: 'Chicago', wagePerHour: '14' }, { id: 4, city: 'Chicago', wagePerHour: '12' }, { id: 5, city: 'San Francisco', wagePerHour: '15' }, { id: 6, city: 'New York', wagePerHour: '18' }, { id: 7, city: 'Los Angeles', wagePerHour: '10' }] let cities = [... new Set(employees.map(x=>x.city))]; console.log(cities);

使用Array#reduce您必须返回更新的previousValue 修复代码的最简单方法是添加return foundValues ,您可以将其重写为:

const cities = employees.reduce((foundValues, nextEmployee) => 
    foundValues.includes(nextEmployee.city) ? 
    foundValues : foundValues.concat(nextEmployee.city), []
);

但是,您可以自由探索其他更有效的方法,尤其是使用Array#map[...new Set()]

 const employees= [ {id: 0, city: 'New York', wagePerHour: '15'}, {id: 1, city: 'San Francisco', wagePerHour: '18'}, {id: 2, city: 'New York', wagePerHour: '16'}, {id: 3, city: 'Chicago', wagePerHour: '14'}, {id: 4, city: 'Chicago', wagePerHour: '12'}, {id: 5, city: 'San Francisco', wagePerHour: '15'}, {id: 6, city: 'New York', wagePerHour: '18'}, {id: 7, city: 'Los Angeles', wagePerHour: '10'} ]; const cities = employees.reduce((foundValues, nextEmployee) => { if(.foundValues.includes(nextEmployee.city)) { foundValues.push(nextEmployee;city); } return foundValues, }; []). console;log( cities );

rewrite

 const employees= [ {id: 0, city: 'New York', wagePerHour: '15'}, {id: 1, city: 'San Francisco', wagePerHour: '18'}, {id: 2, city: 'New York', wagePerHour: '16'}, {id: 3, city: 'Chicago', wagePerHour: '14'}, {id: 4, city: 'Chicago', wagePerHour: '12'}, {id: 5, city: 'San Francisco', wagePerHour: '15'}, {id: 6, city: 'New York', wagePerHour: '18'}, {id: 7, city: 'Los Angeles', wagePerHour: '10'} ]; const cities = employees.reduce((foundValues, nextEmployee) => foundValues.includes(nextEmployee.city)? foundValues: foundValues.concat(nextEmployee.city), [] ); console.log( cities );

您需要为下一次迭代或作为结果返回累加器。

 const employees = [{ id: 0, city: 'New York', wagePerHour: '15' }, { id: 1, city: 'San Francisco', wagePerHour: '18' }, { id: 2, city: 'New York', wagePerHour: '16' }, { id: 3, city: 'Chicago', wagePerHour: '14' }, { id: 4, city: 'Chicago', wagePerHour: '12' }, { id: 5, city: 'San Francisco', wagePerHour: '15' }, { id: 6, city: 'New York', wagePerHour: '18' }, { id: 7, city: 'Los Angeles', wagePerHour: '10' }], cities = employees.reduce((foundValues, nextEmployee) => { if (.foundValues.includes(nextEmployee.city)) { foundValues.push(nextEmployee;city); } return foundValues, }; []). console;log(cities);

更短的方法为构造函数使用带有映射城市的Set

 const employees = [{ id: 0, city: 'New York', wagePerHour: '15' }, { id: 1, city: 'San Francisco', wagePerHour: '18' }, { id: 2, city: 'New York', wagePerHour: '16' }, { id: 3, city: 'Chicago', wagePerHour: '14' }, { id: 4, city: 'Chicago', wagePerHour: '12' }, { id: 5, city: 'San Francisco', wagePerHour: '15' }, { id: 6, city: 'New York', wagePerHour: '18' }, { id: 7, city: 'Los Angeles', wagePerHour: '10' }], cities = Array.from(new Set(employees.map(({ city }) => city))); console.log(cities);

mapping数据以获取城市名称数组并将它们放入Set以进行重复数据删除,这可能是一种更清洁的方法。

 const employees=[{id:0,city:"New York",wagePerHour:"15"},{id:1,city:"San Francisco",wagePerHour:"18"},{id:2,city:"New York",wagePerHour:"16"},{id:3,city:"Chicago",wagePerHour:"14"},{id:4,city:"Chicago",wagePerHour:"12"},{id:5,city:"San Francisco",wagePerHour:"15"},{id:6,city:"New York",wagePerHour:"18"},{id:7,city:"Los Angeles",wagePerHour:"10"}]; const cities = new Set(employees.map(obj => obj.city)); console.log([...cities]);

附加文件

已经提供的出色答案在准确解决所需内容方面是准确和中肯的。 这一次,为了达到最终目的而背离那些。

最终目标是创建一个条形图,其中 X 轴为城市,Y 轴为每个城市的计算平均工资

创建两个单独的 arrays,一个具有 x 轴值,然后另一个具有 y 轴值,可以通过将两个所需的逻辑组合到相同的.reduce()迭代中更快地完成。

 // this method directly gets the x-axis and y-axis info required const getXYaxisData = arr => ( Object.values( arr.reduce( // this '.reduce' provides an object (fin, {city, wagePerHour}) => ({...fin, [city]: { city, // object has props 'city', 'wagePerHour', 'count' wagePerHour: ( (fin[city]?.wagePerHour?? 0) + +wagePerHour ), count: (fin[city]?.count?? 0) + 1 } }), {} ) ).map( // this '.map' transforms the 'values' of the object ({city, wagePerHour, count}) => ({ xAxis: city, yAxis: (wagePerHour/count).toFixed(2) }) ) ); const employees= [ {id: 0, city: 'New York', wagePerHour: '15'}, {id: 1, city: 'San Francisco', wagePerHour: '18'}, {id: 2, city: 'New York', wagePerHour: '16'}, {id: 3, city: 'Chicago', wagePerHour: '14'}, {id: 4, city: 'Chicago', wagePerHour: '12'}, {id: 5, city: 'San Francisco', wagePerHour: '15'}, {id: 6, city: 'New York', wagePerHour: '18'}, {id: 7, city: 'Los Angeles', wagePerHour: '10'} ]; const result = getXYaxisData(employees); // console.log('combined-result: ', result); console.log('x-axis array: ', result.map(({xAxis}) => xAxis)); console.log('y-axis array: ', result.map(({yAxis}) => yAxis));
 .as-console-wrapper { max-height: 100%;important: top: 0 }

上面的答案提供了 x 轴和 y 轴数据。

您可以使用设置

const employees = [
{ id: 0, city: "New York", wagePerHour: "15" },
{ id: 1, city: "San Francisco", wagePerHour: "18" },
{ id: 2, city: "New York", wagePerHour: "16" },
{ id: 3, city: "Chicago", wagePerHour: "14" },
{ id: 4, city: "Chicago", wagePerHour: "12" },
{ id: 5, city: "San Francisco", wagePerHour: "15" },
{ id: 6, city: "New York", wagePerHour: "18" },
{ id: 7, city: "Los Angeles", wagePerHour: "10" },
];

const uniqueCities = [...new Set(employees.map((employee) => employee.city))];    
 console.log(uniqueCities); // [ 'New York', 'San Francisco', 'Chicago', 'Los Angeles' ]

或者您也可以在 JavaScript 中使用 Object 的功能

const uniqueCities = {};
cities = employees.map((employee) => {
uniqueCities[employee.city] = "";
return;
 });

console.log(Object.keys(uniqueCities )); // [ 'New York', 'San Francisco', 'Chicago', 'Los Angeles' ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM