Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a property from an array of objects based on a value : Javascript

I have an array of objects with the following structure:

var arr = [    {      "value": "abc",      "checked": true    },    {      "value": "xyz",      "checked": false    },    {      "value": "lmn",      "checked": true    }  ];    let result = arr.filter(item => item.checked);    console.log(result);

I would want the output to be:

["abc", "lmn"]  

Because those two values have checked: true.

I have tried filtering out based on checked value:

let result = arr.filter(item => item.checked); 

I am getting the objects that has checked property value that is set to true.

Help would be appreciated.

like image 595
joy08 Avatar asked Jul 25 '19 09:07

joy08


People also ask

How do you find the properties of an array of objects?

Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

How do you filter an array of objects based on value?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

use filter and map:

const arr =[{"value":"abc","checked":true},{"value":"xyz","checked":false},{"value":"lmn","checked":true}];     const result = arr.filter(res=>res.checked).map(ele=>ele.value);      console.log(result);
like image 127
Ghoul Ahmed Avatar answered Sep 28 '22 10:09

Ghoul Ahmed