0

I have two local JSON files. I want to add the property of one object from one file to the corresponding object in the other file.

Here is an example..

Array1:

[
  {
    "id": 1,
    "username": "Joe Smith",
    "pic": "images/profile/Joe_smith.jpg"
  },
  {
    "id": 2,
    "username": "Jane Smith",
    "pic": "images/profile/Jane_smith.jpg"
  }
 ]

Array2:

[
 {
   "id": 3,
   "userId": 1,
   "profession": "dentist"
 },
 { 
   "id": 4,
   "userId": 2,
   "profession": "pilot"
 }

The idea is to add the "pic" property from Array1 to the correct object in Array2. If the id from Array1 matches the userId from Array2, it's a correct match. Array2 would end up looking like this:

[
 {
   "id": 3,
   "userId": 1,
   "profession": "dentist",
   "pic": "images/profile/Joe_smith.jpg"
 },
 { 
   "id": 4,
   "userId": 2,
   "profession": "pilot",
   "pic": "images/profile/Jane_smith.jpg"
 }

Afterwards I'm going to use angular to display a name with the face. Hope I explained that ok. Any help would be much appreciated!

user3802738
  • 117
  • 1
  • 6
  • Seems as easy as parsing the JSON, iterating over both arrays and merging the individually objects. Is there something in particular you are having problems with? Do you know how to parse JSON? How to iterate over an array? – Felix Kling Dec 04 '14 at 22:46
  • I know how to iterate over an array and it looks like I might need to do that twice in this case. The parsing thing is new to me though. – user3802738 Dec 04 '14 at 22:59
  • [Parse JSON in JavaScript?](http://stackoverflow.com/q/4935632/218196) – Felix Kling Dec 04 '14 at 23:10

1 Answers1

0

Just for the fun of it. In this example using https://lodash.com.

var people = [
    { "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" }, 
    { "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
    { "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];

var professions = [
    { "id": 3, "userId": 1, "profession": "dentist" },
    { "id": 4, "userId": 2, "profession": "pilot" }
];

var workers = _.map(people, function(human) {
    var work = _.findWhere(professions, { 'userId': human.id });
    return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});

console.log(workers);
marko
  • 2,841
  • 31
  • 37