score:0

Accepted answer
const data = {
  "cases": [{
    "id": 3,
    "photo_id": 14
  }, {
    "id": 2,
    "photo_id": 0
  }, {
    "id": 1,
    "photo_id": 13
  }],
  "photos": [{
    "id": 6,
    "file": "\/images\/1556196076cache_f50f03558d201b8eb2a9af90f0838cee.png"
  }, {
    "id": 11,
    "file": "\/images\/1556198414cache_702c216fa5a4d75d74db237ddf97b012.png"
  }, {
    "id": 12,
    "file": "\/images\/1556198946cache_702c216fa5a4d75d74db237ddf97b012.png"
  }, {
    "id": 13,
    "file": "\/images\/1556726055dewekkpot.nl_short.jpg"
  }, {
    "id": 14,
    "file": "\/images\/1556791722dewekkpot.nl_short.jpg"
  }]
};

const newCases = data.cases.map(({ photo_id, ...rest }) => {
  const obj = { ...rest };
  data.photos.find(ph => {
    if(ph.id === photo_id) {
      obj.file = ph.file;
      return true;
    }
  });
  return obj;
});

console.log(newCases);

score:-1

function addPhotos(cases, photos){
    return cases.map(function (currentCase) {
            const foundPhoto = photos.find(function(currentPhoto){
                return currentPhoto.id === currentCase.photo_id;
            });
            currentCase.photo_path = foundPhoto? foundPhoto.file : "/images/blank_image.jpg";
            return currentCase;
    });
};

console.log(addPhotos(this.state.cases, this.state.photos));
//Output: [{"id":3,"photo_id":14,"photo_path":"/images/1556791722dewekkpot.nl_short.jpg"},{"id":2,"photo_id":0,"photo_path":"images/blank_image.jpg"},{"id":1,"photo_id":13,"photo_path":"/images/1556726055dewekkpot.nl_short.jpg"}]

score:1

addPhotos() {
    var photosMap = this.state.photos.reduce(function (acc, each) {
      acc[each.id] = each; // or you could just save the corresponding filename
      return acc;
    }, {});

    var photoFiles = this.state.cases.reduce(function (acc, each) { // you could alternatively use Array.filter too.
      if (photosMap[each.photo_id]) {
        acc.push(photosMap[each.photo_id]);
      }
      return acc;
    }, []);

    console.log(photoFiles);

}

score:1

const obj = {
    "cases": [{
        "id": 3,
        "photo_id": 14
    }, {
        "id": 2,
        "photo_id": 0
    }, {
        "id": 1,
        "photo_id": 13
    }],
    "photos": [{
        "id": 6,
        "file": "\/images\/1556196076cache_f50f03558d201b8eb2a9af90f0838cee.png"
    }, {
        "id": 11,
        "file": "\/images\/1556198414cache_702c216fa5a4d75d74db237ddf97b012.png"
    }, {
        "id": 12,
        "file": "\/images\/1556198946cache_702c216fa5a4d75d74db237ddf97b012.png"
    }, {
        "id": 13,
        "file": "\/images\/1556726055dewekkpot.nl_short.jpg"
    }, {
        "id": 14,
        "file": "\/images\/1556791722dewekkpot.nl_short.jpg"
    }]
};

const photoIds = obj.cases.reduce((acc, val) => {
    acc[val.photo_id] = val;
    return acc;
}, {});

const res = obj.photos.filter(val => photoIds[val.id]);
console.log(res)

Related Query

More Query from same tag