0

I have two Array of objects as follows.

Array of object 1 ----> [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}]
Array of object 2 -----> [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}]

Is there any short method where I can locationName from first Array, using baseId from Array 2 and push that to new Array of objects,in angular 6. I dont want to use for loop.

2
  • could you post the desired result as JSON? Commented Jul 4, 2018 at 7:24
  • Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. Commented Jul 4, 2018 at 7:24

3 Answers 3

1

The following code should do what you need (comments in code)

// Go throught first array
newArray = array1.map(location => {
    // Look for corresponding object in second array based on Ids
    const foundBase = array2.find(base => base.baseId === location.locationId);
    // If the object is found, return combined object
    if(foundBase){
        return Object.assign(location, foundBase);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

var a = [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}];
    var b = [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}]
    var c = [];

a.map(obj => {
  b.map(res => {
    if (obj.locationId == res.baseId) {
      c.push({
        "locationName": obj.locationName,
        "baseUnit": res.baseUnit
      });
    }
  });
});


console.log(c);

Comments

1

Reduce your arrays

Here you can see that it is possible to use .reduce on an Array to iterate over the array whilst generating a new one:

let array1 = [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}]
let array2 = [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}]

// Combine objects in array
array1.reduce((newArray, _, index) => newArray.concat({...array1[index], ...array2[index]}), [])

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.