2

I have a $scope variable that contains an array of objects.

$scope.arrayOfObjects = [{key:"ASS"}, 
{key:"CRT"},{key:"PRD"}]

And I have an array with this value

var arr = ["ASS", "CRT"]

I would update the array of objects with only the value of the keys into that are only in the array. How can do it?

$scope.arrayOfObjects = [{key:"ASS"},
{key:"CRT"}]

1 Answer 1

1

Use array.map:

var arr = ["ASS", "CRT"];
var objArr = arr.map( _ => ({ key: _ }) );
console.log(objArr);    


Or maybe

var arrayOfObjects =  [
   {key:"ASS"}, {key:"CRT"}, {key:"PRD"}
];
var arr = ["ASS", "CRT"];
var objArr = arr.map( _ => arrayOfObjects.find( _1 => _1.key == _ ) );
console.log(objArr);    

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

2 Comments

I mean this is absolutely what I would do but why are you using _ as the variable name? This could be really confusing especially to some beginners. Is there any reason or just personal preference (tight code)?
In the Scala language underscore (_) is used regularly in specifying the parameter of a function literal. Other people commonly use it in JavaScript. It is a matter of personal preference and style.

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.