一个对象包含一组对象 - 每个对象都有一个id和名称,我该如何分开它们?

时间:2015-06-03 23:53:40

标签: javascript jquery arrays multidimensional-array

目前我有这个对象:

obj = [object{id: 1, name: test, parentID: 3}, object{id:1, name: another, parentID: 5}, object{id:2, name:something, parentID: 1}].

最终我想要一个以不同方式构建的对象。 所以它是对象,但如果我的标识符为1,它有一个名称集合(在本例中为test,另一个)。如果它是2,它只显示'

我无法弄清楚这应该是什么样的,可能是这样的? obj = [[1,test], [1,another], [2,something]]对吧?

因此,如果我调用obj [1],我会得到一个倍数(测试,另一个等)。

有人可以帮忙吗?我现在已经花了一个小时摆弄这个,我只是不明白。

我构建了这样的原始对象:

var obj = Array();
//loop here
  var obj = {
     id: id,
     name: name,
     parentID: parentID
  };
  obj.push(obj);

我做错了什么?我怎样才能解决这个问题?这让我成为对象中的对象,但我真的想要ID和名称中的id和名字。我的最终目标是迭代这一点。所以我只得到任何类似ID的名称,这样我可以使用它来填充数组或计数

因此:

if(obj[id] == 1){
  //put the name in the new array
}

是我的最终目标。但是我对最初的对象创建感到有些失落,所以现在它已经很乱了。

3 个答案:

答案 0 :(得分:2)

尝试:

var obj = [{id: 1, name: "Foo"}, {id: 2, name: "Fee"}, {id: 3, name: "Fii"}];
var result = [], item, i = 0;
while(item = obj[i++]){
    for(key in item){
        if(key === "id") continue; //remove this line if you want to keep the ID also in the array
        !result[i] && (result[i] = []);
        result[i].push(item[key]);
    }
}
console.log(result[1]); // --> ["Foo"]

答案 1 :(得分:1)

您要做的是一次遍历对象数组。每次通过时,您都要检查新对象以查看该ID是否存在。如果是,请添加名称。如果没有,请为该id创建一个新条目,并添加一个包含一个条目的数组。注意,这不会处理重复的名称(它只是再次添加)。

var array = [{id:1, name:"test"}, 
             {id:1, name:"another"},
             {id:2, name:"something"}];

var result = {};
array.forEach(function(item) {
  if (result[item.id]) {
    result[item.id].push(item.name);
  }
  else {
    result[item.id] = [item.name];
  }
});

console.log(result[1]);

答案 2 :(得分:1)

我的看法:

var sourceObject=[{id:0,name:'Tahir'},{id:0,name:'Ahmed'},{id:1,name:'David'},{id:1,name:'G'},{id:2,name:'TA'},{id:3,name:'DG'}];
function getNames(id){
    var names=[],length=sourceObject.length,i=0;
    for(i;i<length;i+=1){
        if(sourceObject[i].id===id){
            names[names.length]=sourceObject[i].name;
        }
    }
    return names;
}
console.log(getNames(1));