0

Say, I have some code which looks like follows:-

objects1.forEach(function check(o1) {
    if (o1.name === object.name) {
        object.name = object.name + objectType;
    }
});

objects2.forEach(function ifNameMatch(o2) {
    if (o2.name === object.name) {
        object.name = object.name + objectType;
    }
});

Is there any way I could replace this 2 forEach by one or write it in the more better way?

Any suggestion that you could give would be appreciated.

1
  • Are you looking for answer with ES5 or ES6? Commented Nov 1, 2017 at 7:47

1 Answer 1

1

First I would create a generator for each object I have to do it, if its a repetitive process, then I would return a function that would process collections which is objects1 or objects2 in your scenario.

let nameMatchGenerator = (object, objectType)  => {
return (collections) => { 
  return collections.forEach(collection) => {
    collection.forEach(o => {
      if (o.name === object.name) {
        object.name = object.name + objectType;
      }
    })
  }
}
let nameMatch = (object, objectType);
nameMatch([objects1, objects2]) // you can use this function to repeat 
                             // the process for as many collections
Sign up to request clarification or add additional context in comments.

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.