简体   繁体   English

如果为true,则从数组中的对象获取特定属性

[英]Get a specific property from an object in an array if true

I have a object that looks like this: 我有一个看起来像这样的对象:

export default class Widget {
public title: string;
public url: string;
public icon: string;
public id: string;
public defaultWidget: boolean;
  }

I have an array with all the widgets, allWidgets. 我有一个包含所有小部件allArrays的数组。 I want to extract the id from this array WHEN the defaultWidget is true. 当defaultWidget为true时,我想从此数组中提取ID。

So I want to extract a property from this object (id) WHEN another property (defaultWidget) is true. 因此,当另一个属性(defaultWidget)为true时,我想从此对象(id)中提取一个属性。 So far I have: 到目前为止,我有:

const newArray = allWidgets.map(element => element.defaultWidget);

However, it only returns true for every true object it have. 但是,它只为它拥有的每个真实对象返回true。 But I want it to return the ID where the defaultWidget is true. 但是我希望它返回defaultWidget为true的ID。

You could use filter to get widgets with defaultWidget === true and then use map to get ids. 您可以使用filter获取具有defaultWidget === true窗口小部件,然后使用map获取ID。

Both filter and map will create new arrays. filtermap都会创建新的数组。

Or you could try use reduce to compose all of it. 或者,您可以尝试使用reduce组合所有内容。

In case of reduce you will create new array once. 如果是reduce ,则将创建一次新数组。

const newArray = allWidgets.filter(widget => widget.defaultWidget).map(widget => widget.id)

// or

const newArray = allWidgets.reduce((acc, elem) => {
  if (elem.defaultWidget) {
    acc.push(elem.id);
  }

  return acc;
}, []);

const newArray = allWidgets.filter(obj => obj.defaultWidget).map(obj => obj.id); const newArray = allWidgets.filter(obj => obj.defaultWidget).map(obj => obj.id);

The above array will give you the list of id's where defaultWidget is true. 上面的数组将为您提供id的列表,其中defaultWidget为true。

Here Filter will filters the array based on the condition and map creates a new array containing only id's 这里的Filter将根据条件过滤数组,然后map创建一个仅包含id的新数组

in JavaScript you can try this code: returns list of ids if married = true 在JavaScript中,您可以尝试以下代码: returns list of ids if married = true

// Try edit msg
var emps = [
 {id: 1, name: "Employee1", married: true},
 {id: 2, name: "Employee1", married: false},
 {id: 3, name: "Employee1", married: true}
]

// getting list of ids of employees if married is true
var idList = emps.map(obj => {
  if (obj['married'] == true) {
    return obj.id 
  } 

})

// removing null values from list 
idList = idList.filter(ele => ele!=null);

console.log(idList);   

// output: [1, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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