sri harsha sri harsha - 4 months ago 17
AngularJS Question

Compare array of objects by property with key of another object

I want to compare the data.examples array object name.value property value with wcObject.notCoveredList key, If the key matches I want to push all matched values of wcObject to an array inorder to display in UI. If the key doesn't match, I want the name.desc property value of data.examples array object to be pushed by removing the not covered text at the end.

data = {
examples : [
{
name: {
value:"someOne",
desc: "some random word not covered"
},
type: {
value:"General",
desc:"General"
}
}, {
name: {
value:"secondOne",
desc: "second on in the queue not covered"
},
type: {
value:"General",
desc:"General"
}
}, {
name: {
value:"thirdOne",
desc: "third one from the last not covered"
},
type: {
value:"General",
desc:"General"
}
}
]

}

wcObject = {
notCoveredList : [
{ someOne: "anyone can start " },
{ secondOne: "second One cannot start" },
{ thirdOne: "third One can be allowed" }
]
}

Answer

So, this code:

  1. Builds up a filter object. We grab all the keys of wcObject.notCoveredList, and make them keys on a single object (with an undefined value), so that we can look up those keys with a single hasOwnProperty() call instead of iterating over an array when we need to filter.
  2. Maps every member of the data.examples array to either its own name.desc property or [stripped of ' not covered'] name.value property.

.

wcNotCoveredKeys = wcObject.notCoveredList.reduce((memo, item) => {
  memo[Object.keys(item)[0]] = undefined;
  return memo;
}, {})

forUI = data.examples.map(example => {
  if (wcNotCoveredKeys.hasOwnProperty(example.name.value)) {
    return example.name.value;
  }
  else {
    notCoveredString = example.name.desc;
    cutOutIndex = notCoveredString.indexOf(' not covered');
    return notCoveredString.slice(0, cutOutIndex)
  }
});

(updated to integrate string slicing)

Just to be clear: if you removed the second item from wcObject.notCoveredList, then the output you'd get in forUI (given the example data structures/values you provided) would be

["someOne", "second on in the queue", "thirdOne"]