如何从 JavaScript 中的对象数组中获取不同的值? [英] How to get distinct values from an array of objects in JavaScript?

查看:31
本文介绍了如何从 JavaScript 中的对象数组中获取不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

var 数组 =[{姓名":乔",年龄":17},{姓名":鲍勃",年龄":17},{姓名":卡尔",年龄":35}]

能够获得所有不同年龄的数组的最佳方法是什么,以便我得到以下结果数组:

[17, 35]

有什么方法可以替代地构造数据或更好的方法,这样我就不必遍历每个数组来检查age"的值并检查另一个数组是否存在,如果不存在则添加它?

如果有什么方法可以不重复地提取不同的年龄...

目前我想改进的低效方式......如果这意味着不是数组"是一个对象数组,而是一个具有某些唯一键(即1,2,3")的对象映射"那也没关系.我只是在寻找最高效的方式.

以下是我目前的做法,但对我来说,迭代似乎只是效率低下,即使它确实有效...

var distinct = []for (var i = 0; i < array.length; i++)if (array[i].age not in distinct)distinct.push(array[i].age)

解决方案

如果你使用的是 ES6/ES2015 或更高版本,你可以这样做:

const 数据 = [{组:'A',名称:'SD'},{组:'B',名称:'FI'},{组:'A',名称:'MM'},{组:'B',名称:'CO'}];const unique = [...new Set(data.map(item => item.group))];//['A', 'B']

这里是一个示例.>

Assuming I have the following:

var array = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35}
    ]

What is the best way to be able to get an array of all of the distinct ages such that I get an result array of:

[17, 35]

Is there some way I could alternatively structure the data or better method such that I would not have to iterate through each array checking the value of "age" and check against another array for its existence, and add it if not?

If there was some way I could just pull out the distinct ages without iterating...

Current inefficent way I would like to improve... If it means that instead of "array" being an array of objects, but a "map" of objects with some unique key (i.e. "1,2,3") that would be okay too. Im just looking for the most performance efficient way.

The following is how I currently do it, but for me, iteration appears to just be crummy for efficiency even though it does work...

var distinct = []
for (var i = 0; i < array.length; i++)
   if (array[i].age not in distinct)
      distinct.push(array[i].age)

解决方案

If you are using ES6/ES2015 or later you can do it this way:

const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']

Here is an example on how to do it.

这篇关于如何从 JavaScript 中的对象数组中获取不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆