繁体   English   中英

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

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

我有一个看起来像这样的对象:

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

我有一个包含所有小部件allArrays的数组。 当defaultWidget为true时,我想从此数组中提取ID。

因此,当另一个属性(defaultWidget)为true时,我想从此对象(id)中提取一个属性。 到目前为止,我有:

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

但是,它只为它拥有的每个真实对象返回true。 但是我希望它返回defaultWidget为true的ID。

您可以使用filter获取具有defaultWidget === true窗口小部件,然后使用map获取ID。

filtermap都会创建新的数组。

或者,您可以尝试使用reduce组合所有内容。

如果是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);

上面的数组将为您提供id的列表,其中defaultWidget为true。

这里的Filter将根据条件过滤数组,然后map创建一个仅包含id的新数组

在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