I m not sure what you re trying to do, but maybe you just need to aggregate the data?
var data = [
{ name: "portrait", owner: "Jon" },
{ name: "house", owner: "Jim" },
{ name: "portrait", owner: "Jim" },
{ name: "portrait", owner: "Jane" },
{ name: "cat", owner: "Jane" }
];
var byName = {};
for (var i = 0, l = data.length; i < l; ++i) {
if (!byName[data[i].name]){
byName[data[i].name] = [];
}
byName[data[i].name].push(data[i].owner);
}
// byName == {portrait: ["Jon", "Jim", "Jane"], house: ["Jim"], cat: ["Jane"]}
var byOwner = {};
for (var i = 0, l = data.length; i < l; ++i) {
if (!byOwner[data[i].owner]) {
byOwner[data[i].owner] = [];
}
byOwner[data[i].owner].push(data[i].name);
}
Or maybe you like this better:
var data = [
{ name: "portrait", owner: "Jon" },
{ name: "house", owner: "Jim" },
{ name: "portrait", owner: "Jim" },
{ name: "portrait", owner: "Jane" },
{ name: "cat", owner: "Jane" }
];
var byName = [];
for (var i = 0, l = data.length; i < l; ++i) {
var done = false;
for (var j = 0, k = data.length; j < k; ++j) {
if (byName[j] && byName[j].name == data[i].name) {
byName[j].data.push(data[i].owner);
done = true;
}
}
if (!done) {
byName.push({name: data[i].name, data: [data[i].owner]});
}
}
/*
byName == [
{name: "portrait", data: ["Jon", "Jim", "Jane"]},
{name: "house", data: ["Jim"]},
{name: "cat", data: ["Jane"]}
] */
Because posting random code is fun and you know it!