简体   繁体   English

Ramda 或 ES6 - 在过滤对象数组后返回对象属性的值

[英]Ramda or ES6 - Return the value of an Object Property, after filtering an Array of Objects

I want to return one of the properties of an object, if the value of another property matches a constant.如果另一个属性的值与常量匹配,我想返回对象的一个​​属性。

Examples:例子:

// The Array
[
 {name: "Name1", description: "Name1 Description", enabled: true},
 {name: "Name2", description: "Name2 Description", enabled: false},
 {name: "Name3", description: "Name3 Description", enabled: false}
]

// The Constant
enum constant {
  Name1 = 'Name1',
  Name2 = 'Name2',
  Name3 = 'Name3'
}

// What I want to return
// Value of enabled property, for the matching object

This is the code I wrote:这是我写的代码:

const filterBasedOnToggle = (featureTogglesArray: IFeatureToggle[], featureToggle: Toggle): boolean[] => {
  return featureTogglesArray.filter((feature: IFeatureToggle) => feature.name === featureToggle).map(featureProperty => featureProperty.enabled);
};

This as you can see by the Typings, is returning an Array of Boolean value.正如您在 Typings 中看到的那样,它返回一个布尔值数组。 I want to return the plain value.我想返回普通值。 Any Ideas?有任何想法吗? Thank you!!谢谢!!

Didn't check if your code works, but as you said it returns a boolean array, so try using array.find to get the first match.没有检查您的代码是否有效,但正如您所说,它返回一个布尔数组,因此请尝试使用array.find获取第一个匹配项。

  const MATCH = featureTogglesArray.find((feature: IFeatureToggle) => feature.name === featureToggle);
  return MATCH === undefined ? false : MATCH.enabled;

Are you looking for something like this?你在寻找这样的东西吗?

 const filterBasedOnToggle = (toggles) => (searchName) => { const feature = toggles .find (({name}) => name == searchName) || {} return feature .enabled } const featureToggles = [{name: "Name1", description: "Name1 Description", enabled: true}, {name: "Name2", description: "Name2 Description", enabled: false}, {name: "Name3", description: "Name3 Description", enabled: false}]; const enabledByName = filterBasedOnToggle (featureToggles); console .log (['Name1', 'Name2', 'Name3', 'Name4'] .map (enabledByName)) //~> [true, false, false, undefined]

This version uses find instead of filter to match on only the first one ... which was probably the signature issue with your version.这个版本使用find而不是filter来匹配第一个......这可能是你的版本的签名问题。 It returns undefined if the value isn't matched, but you could easily make that false if you liked.如果值不匹配,它将返回undefined ,但如果您愿意,您可以轻松地将其false You could of course write this with Ramda functions, but I don't see much there that would make this much simpler.你当然可以用 Ramda 函数来写这个,但我没有看到太多能让这变得更简单的东西。

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

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