javascript - How to merge data across multiple objects -
javascript - How to merge data across multiple objects -
example object:
{ 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"] } ] }
using object need display each place , names associated place this:
usa jimmy, serena, richard canada jimmy, serena state of japan serena, richard thailand serena china richard united kingdom of britain and northern republic of ireland jimmy, richard federal republic of germany rachel
here's current limited progress.
i can't seem figure out how limited javascript experience. using underscorejs, have figure out how display each person's name , places with, that's not want. need merged shown above. here's i've come far...
_.each(people, function (value, key) { var name = person[key].name; var place = person[key].place; homecoming name + '<br>' + place; });
which outputs...
jimmy usa,canada,united kingdom serena usa,japan,canada,thailand richard usa,japan,china,united kingdom rachel federal republic of germany
can of assistance? prefer reply using underscorejs, open other forms of javascript.
just parse array countries , add together matching names. 2 nested loops suffice:
var arr = [/*...*/];// initial array // object stores target construction var store = {}; // every person in list .. arr.foreach(function(person) { // every country, person has visited person.place.foreach(function(place) { // store know country? if (!store.hasownproperty(place)) { // no, create store[place] = []; } // add together person the country store[place].push(person.name); }); }); console.log(store);
demo jsfiddle
javascript node.js underscore.js
Comments
Post a Comment