-1

I am trying to display the name of persons whose favorite color is pink from an array of multiple jsons. Which method or logic I should use in javascript or jQuery?

var person = [{
"name":"Angel",
"age":23,
"color":[ "pink", "purple", "white" ]
},
{
"name":"Harry",
"age":20,
"color":[ "pink", "yellow" , "red" ]
},
{
"name":"Ella",
"age":21,
"color":[ "green", "gray", "black" ]
}];
3

2 Answers 2

0

You can use the Array.filter and Array.map functions

var person = [{
"name":"Angel",
"age":23,
"color":[ "pink", "purple", "white" ]
},
{
"name":"Harry",
"age":20,
"color":[ "pink", "yellow" , "red" ]
},
{
"name":"Ella",
"age":21,
"color":[ "green", "gray", "black" ]
}];

var names = person.filter(x => x.color.includes('pink')).map(x => x.name);
console.log(names);

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

Comments

0

Use filter and forEach

var person = [{
"name":"Angel",
"age":23,
"color":[ "pink", "purple", "white" ]
},
{
"name":"Harry",
"age":20,
"color":[ "pink", "yellow" , "red" ]
},
{
"name":"Ella",
"age":21,
"color":[ "green", "gray", "black" ]
}];
var arr=[];
person.forEach(function(e){
if(e.color.filter(function(k){return k=="pink"}).length>=1)
arr.push( e.name)
})
console.log(arr)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.