0
const object1: [{
  "code": "lap-143240121",
  "index": 0
}, {
  "code": "lap-15040293",
  "index": 1
}, {
  "code": "lp-1504444",
  "index": 2
}, {
  "code": "lp-150440987",
  "index": 3
}]

const object2: [{
  "code": "lap-143240121",
  "name": "name1"
}, {
  "code": "lap-15040293",
  "name": "name2"
}, {
  "code": "lp-1504444",
  "name": "name3"
}]

I would like to map those two list of object by code to have an output like :

const objectResult: [{
  "code": "lap-143240121",
  "index": 0,
  "name": "name1"
}, {
  "code": "lap-15040293",
  "index": 1,
  "name": "name2"
}, {
  "code": "lp-1504444",
  "index": 2,
  "name": "name3"
}]
3
  • 4
    Please tell what you have tried. Commented Jan 19, 2021 at 5:25
  • 1
    Pretty easy answer there, but I agree with @angelo, you gotta at least make an effort to solve this. Commented Jan 19, 2021 at 5:29
  • thanks gentleman. It's because I didn't succeed it that I posted. I didn't know how to add a value from one to another. Here is my code for (var val of obj1){ var v = obj2.filter(item=>item.code === val.code) let trial = obj2.filter(function (obj) { return obj.code === val.code; }).map(function (os) { return os.code; }) Commented Jan 19, 2021 at 5:37

2 Answers 2

1

Use map to iterate object2 and then use rest operator to return an object which consist of all the elements and the name from object1

const object1 = [{
  "code": "lap-143240121",
  "index": 0
}, {
  "code": "lap-15040293",
  "index": 1
}, {
  "code": "lp-1504444",
  "index": 2
}, {
  "code": "lp-150440987",
  "index": 3
}]

const object2 = [{
  "code": "lap-143240121",
  "name": "name1"
}, {
  "code": "lap-15040293",
  "name": "name2"
}, {
  "code": "lp-1504444",
  "name": "name3"
}];


const obj3 = object2.map((item) => {
  return {
    ...item, // will consist all the items from object2
    // get index from object1 where the code matches
    index: object1.find(elem => elem.code === item.code).index 
  }
});

console.log(obj3)

Sign up to request clarification or add additional context in comments.

Comments

1
  • transform the object1 to Map with value of code as key and whole object as value
  • iterate on object2 search code from object2 in the above created map, if found merge the properties

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.