获取具有每个唯一属性值的一个对象

时间:2015-01-20 12:55:31

标签: javascript

我有一个包含多个对象的数组。我希望得到第一个对象(顺序很重要),每个唯一值为ref

var data = [
    { id: "asghalk", etc: "Hello World", ref: "ad23f1" },
    { id: "glfdknd", etc: "Testing, 12", ref: "912b12" },
    { id: "lka09go", etc: "Some String", ref: "ad23f1" },
    { id: "klghame", etc: "Hello World", ref: "124e12" },
    { id: "glkahma", etc: "Hello World", ref: "124e12" }
];

从此,我想:

var result = [
    { id: "asghalk", etc: "Hello World", ref: "ad23f1" },
    { id: "glfdknd", etc: "Testing, 12", ref: "912b12" },
    { id: "klghame", etc: "Hello World", ref: "124e12" },
]

(仅保留具有新ref的对象。)欢迎任何提案(包含任何依赖项)。

4 个答案:

答案 0 :(得分:2)

以下代码在数组中查找' ref'的每个唯一值的第一条记录:

var data = [
    { id: "asghalk", etc: "Hello World", ref: "ad23f1" },
    { id: "glfdknd", etc: "Testing, 12", ref: "912b12" },
    { id: "lka09go", etc: "Some String", ref: "ad23f1" },
    { id: "klghame", etc: "Hello World", ref: "124e12" },
    { id: "glkahma", etc: "Hello World", ref: "124e12" }
];

var result = [];
var found = {};
for (idx = 0; idx < data.length; idx++) {
    if (!found[data[idx].ref]) {
        found[data[idx].ref] = true;
        result.push(data[idx]);
    }
}

代码维护一个已经找到的refs表,如果ref还没有被看到,只会将对象添加到结果数组中。

答案 1 :(得分:1)

 _.uniq(data,'ref');

我在这里使用了lodash js库方法uniq,通过这个你可以获得包含uniq refs的对象

答案 2 :(得分:0)

我建议使用像字典/地图

这样的空js对象
<html>
    <script>
        var data = [
            { id: "asghalk", etc: "Hello World", ref: "ad23f1" },
            { id: "glfdknd", etc: "Testing, 12", ref: "912b12" },
            { id: "lka09go", etc: "Some String", ref: "ad23f1" },
            { id: "klghame", etc: "Hello World", ref: "124e12" },
            { id: "glkahma", etc: "Hello World", ref: "124e12" }
        ];

        var result = [];
        var map = {};

        for(var i=0;i<data.length;i++){
            map[ data[i].ref ] = data[i];
        }

        for(var item in map){
            //document.write("[item]"+item + "<br>");
            result.push(map[item]);
        }

        for(var i=0;i<result.length;i++){
            document.write(JSON.stringify(result[i]) + "<br>");
        }
    </script>
</html>

答案 3 :(得分:0)

var data = [
    { id: "asghalk", etc: "Hello World", ref: "ad23f1" },
    { id: "glfdknd", etc: "Testing, 12", ref: "912b12" },
    { id: "lka09go", etc: "Some String", ref: "ad23f1" },
    { id: "klghame", etc: "Hello World", ref: "124e12" },
    { id: "glkahma", etc: "Hello World", ref: "124e12" }
];
result = new Array();
for(i=0;i<data.length;++i){
  var descriptor=Object.getOwnPropertyDescriptor(data[i], "ref");
    a=false;
    while(a!=true){
      for(j=i;j<data.length;++j)
       if(Object.getOwnPropertyDescriptor(data[i], "ref").value==Object.getOwnPropertyDescriptor(data[j], "ref").value){
           result.push(data[i]);
           a=true; break;
       }
    }
}