如何跨多个对象合并数据

时间:2014-06-21 14:42:46

标签: javascript node.js underscore.js

示例对象:

{
people: [
  {
    "Name": "Jimmy",
    "Place": ["USA", "Canada", "United Kingdom"]
  },
  {
    "Name": "Serena",
    "Place": ["USA", "Japan", "Canada", "Thailand"]
  },
  {
    "Name": "Richard",
    "Place": ["USA", "Japan", "China", "United Kingdom"]
  },
  {
    "Name": "Rachel",
    "Place": ["Germany"]
  }
]
}

使用这个对象,我需要显示每个地方以及与该地点相关联的名称,如下所示:

USA
Jimmy, Serena, Richard

Canada
Jimmy, Serena

Japan
Serena, Richard

Thailand
Serena

China
Richard

United Kingdom
Jimmy, Richard

Germany
Rachel

这是我当前有限的进展。

我似乎无法通过有限的JavaScript体验弄清楚如何做到这一点。使用下划线,我已经弄清楚如何显示每个人的姓名和他们所在的地方,但这不是我想要的。我需要它合并如上所示。这就是我到目前为止所提出的......

_.each(people, function (value, key) {
  var name = person[key].Name;
  var place = person[key].Place;
  return name + '<br>' + place;
});

哪些输出......

Jimmy
USA,Canada,United Kingdom

Serena
USA,Japan,Canada,Thailand

Richard
USA,Japan,China,United Kingdom

Rachel
Germany

任何人都可以提供帮助吗?我更喜欢使用underscoreJS的答案,但我对其他形式的JavaScript持开放态度。

2 个答案:

答案 0 :(得分:1)

只需解析所有国家/地区的数组并添加匹配的名称。两个嵌套循环就足够了:

var arr = [/*...*/];// initial array

// object stores the target structure
var store = {};

// for every person in the list ..
arr.forEach(function(person) {
    // for every country, the person has visited
    person.Place.forEach(function(place) {
        // does the store know the country?
        if (!store.hasOwnProperty(place)) {
            // no, create it
            store[place] = [];
        }
        // add the person the the country
        store[place].push(person.Name);
    });
});

console.log(store);

demo jsfiddle

答案 1 :(得分:0)

您需要首先合并地点并循环浏览地点并打印名称(如果匹配):

var _ = require('underscore');
var places = [];
var os = require('os');
var i, j, len, len1, names;

for (i = 0, len = people.length; i < len; i++) {
   places = _.union(places, people[i].Place);
}
for (i = 0, len = places.length; i < len; i++) {
  console.log(places[i]);
  names = []
  for (j = 0, len1 = people.length; j < len1; j++) {
    if (_.indexOf(people[j].Place, places[i]) >= 0) {
      names.push(people[j].Name);
    }
  }
  console.log("  " + names.join(', ') + os.EOL);
}