根据值从对象数组中选择一个属性:Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/57198332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select a property from an array of objects based on a value : Javascript
提问by vjr12
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.
因为那两个values 有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 checkedproperty value that is set to true.
我正在获取checked属性值设置为 的对象true。
Help would be appreciated.
帮助将不胜感激。
回答by Kobe
You can use reducewith a check if checkedis true, then pushthe value to the accumulator - there is no need for 2 loops:
您可以使用reduce检查是否checked为真,然后push是累加器的值 - 不需要 2 个循环:
const arr = [{"value": "abc","checked": true},{"value": "xyz","checked": false},{"value": "lmn","checked": true}]
const filtered = arr.reduce((a, o) => o.checked ? a.concat(o.value) : a, [])
console.log(filtered)
As pointed out by assoron, pushis faster than concat, so you could write that function as the following:
正如assoron所指出的,push比 快concat,因此您可以将该函数编写如下:
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)
回答by Ghoul Ahmed
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);
回答by Hyman Bashford
Firstly, that's not valid JS - you need to swap your brackets and braces. Arrays use [], and objects use {}, not the other way around.
首先,这不是有效的 JS - 你需要交换你的括号和大括号。数组使用[],对象使用{},而不是相反。
Secondly, you should first filterout the wanted objects based on the checkedproperty, then use mapto extract the properties you want:
其次,您应该首先filter根据checked属性取出想要的对象,然后使用map提取您想要的属性:
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);
回答by MH2K9
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.
Array.prototype.reduce()可能会帮助你。reduce()callback 有两个参数,第一个参数是旧的/上一次迭代值,第二个参数是当前的迭代值/元素。
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)
回答by Nick Parsons
You can use .reduceto essentially mapand filterat the same time. Below I have built an accumulated array using [v].slice(+!c)which will add the value to the (accumulated) array if cis true, else, it will not add it to the array (as [v].slice(+!false)will return [], and [...[]]will give []):
您可以使用.reduce基本上map和filter在同一时间。下面我建立了一个累积数组[v].slice(+!c),如果c为真,它将把值添加到(累积)数组中,否则,它不会将它添加到数组中([v].slice(+!false)将返回[],并[...[]]给出[]):
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);
回答by Rajaprabhu Aravindasamy
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.
不要把事情复杂化。只需使用一个普通的 for 循环并保存运行时。即使您的数组中的所有元素都具有已检查的属性,以下内容也只会迭代数组一次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/.filterthey 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.
如果您查看.map/ 的内部实现,.filter它们将使用 while 循环迭代数组。假设您有一个数据,所有元素都设置为选中的 true,那么 filter 将遍历所有元素,map 将再次遍历它们以从中获取值。
回答by Saurabh Yadav
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
创建一个泛型函数,您只需要在其中传递键值和数组,它将过滤掉基本参数上的 arry
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));
回答by Luca T
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 filterand map, as that loops over your list two times):
这里的所有解决方案都是有效的,但是如果您更喜欢使用 ES6+ 语法的更迭代方法,您可以明确地对您的项目进行 each 循环,以便让您的读者非常清楚您的意图(另外,它比连接filterand更快map,因为循环在你的清单上两次):
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);
回答by ellipsis
Fix the data structure and use filter and map
修复数据结构,使用filter和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}))
回答by Hardik Shah
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);

