简体   繁体   中英

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 value s 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.

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);

You can use reduce and check if the checked property is true, then push (As pointed out by assoron ) the value to the accumulator - there is no need for 2 loops:

 const arr = [ { "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true } ] const filtered = arr.reduce((a, o) => (o.checked && a.push(o.value), a), []) console.log(filtered)

Firstly, that's not valid JS - you need to swap your brackets and braces. Arrays use [] , and objects use {} , not the other way around.

Secondly, you should first filter out the wanted objects based on the checked property, then use map to extract the properties you want:

 const arr =[{"value":"abc","checked":true},{"value":"xyz","checked":false},{"value":"lmn","checked":true}]; const res = arr.filter(({ checked }) => checked).map(({ value }) => value); console.log(res);

Do not make the things complex. Just use a plain for loop and save the runtime. The following will iterate the array only once even if you have all the elements in your array has a checked property true .

 var arr = [{ "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true }]; var results = []; for(var i=0; i<arr.length-1; i++) { if(arr[i].checked === true){ results.push(arr[i].value) } }

If you look into this internal implementation of .map / .filter they will iterate the array using a while loop. Let's say if you have a data that has all the elements set with checked true, then filter will iterate over all the elements once and again map will iterate over them to fetch the value from it.

Array.prototype.reduce() might help you. reduce() callback takes two arguments, who's first argument is the old/previous iteration value and second argument is the current iteration value/element.

So using this function we can holds our current iteration values to the previous iteration value (total values).

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

 var arr = [{"value": "abc","checked": true},{"value": "xyz","checked": false},{"value": "lmn","checked": true}] const result = arr.reduce((acc, cur) => ((cur.checked && acc.push(cur.value)), acc), []) console.log(result)

You can use .reduce to essentially map and filter at the same time. Below I have built an accumulated array using [v].slice(+!c) which will add the value to the (accumulated) array if c is true, else, it will not add it to the array (as [v].slice(+!false) will return [] , and [...[]] will give [] ):

 const arr = [{ "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true }]; const res = arr.reduce((a, {value:v, checked:c}) => [...a, ...[v].slice(+!c)], []); console.log(res);

Fix the data structure and use filter and map

 var obj = [ { "value" : "abc", "checked" : true }, { "value" : "xyz", "checked" : false }, { "value" : "lmn", "checked" : true } ] console.log(obj.filter(function(e){return e.checked==true}).map(function(e){return e.value}))

All solutions here are valid, but if you prefer a more iterative approach with ES6+ syntax you can explicitly each-loop over your items in order to make your intentions super-clear for your readers (plus, it's faster than concatenating filter and map , as that loops over your list two times):

 const items = [ { "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true } ]; const formattedListOfFilteredItems = []; for (item of items) { if (item.checked) formattedListOfFilteredItems.push(item.value); } console.log(formattedListOfFilteredItems);

create a generic function in which you just need to pass the key value and array and it will filter out the arry on the basic of parameters

 var arr = [
          {
            "value": "abc",
            "checked": true
          },
          {
            "value": "xyz",
            "checked": false
          },
          {
            "value": "lmn",
            "checked": true
          }
        ]


            function filterList(keyValue, list) {
                let filteredList = [];
                for(let i = 0; i < list.length; i++) {
                    if(list[i]["checked"] === keyValue) {
                        filteredList.push(list[i]["value"]);
                    }
                }
                return filteredList;
            }

    console.log(filterList(true, arr));

Using map and filter function as below:

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

var a = [];
arr.forEach( (i)=> i.checked ? a.push(i.value) :null  )

It will evaluate the method passed in foreach for each element of the array and check if the element.checked is true it will push the element.value in the array a which is the desired output.

You are not pushing the value in the new array. Try this it is working properly.

const arr = [{ "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true }]
let result = []
let check = arr.filter((val) => {
    if (val.checked) {
        result.push(val.value)
    }
})
console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM