过滤对象数组中与值对应的元素。

huangapple go评论70阅读模式
英文:

filter the elements in object array corresponding to value

问题

我有一个对象

let arr = { tp: 1, op: 1, lp: 0, co: 0 }

我想将值为1的元素推送到一个新数组中

预期的arr应该是{tp, op}

英文:

I have an object

let arr={tp:1, op:1, lp:0, co:0}

I want to push the element into a new array whose values is 1
Expected arr is like {tp,op}

答案1

得分: 1

你确实有一个类似于“关联数组”(即映射)的对象。

如果你想获取值为1的键(名称),你可以使用以下代码:

  1. 转换为条目数组
  2. 按值筛选
  3. 提取名称
let arr = {tp: 1, op: 1, lp: 0, co: 0}

const ones = Object.entries(arr)
  .filter(([_, value]) => value === 1)
  .map(([name]) => name)

console.log(ones)
英文:

You do have an object that is more like an "associated array" (i.e. a map).

If you want to get names (keys) which value is 1. You can use the following code:

  1. Convert to an array of entries
  2. Filter by value
  3. Extract name

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr={tp:1, op:1, lp:0, co:0}

const ones = Object.entries(arr)
  .filter(([_, value]) =&gt; value === 1)
  .map(([name]) =&gt; name)

console.log(ones)

<!-- end snippet -->

答案2

得分: 0

这是一个对象。迭代对象,如果相应的值等于1,则将属性键推送到一个数组中。

const obj = { tp: 1, op: 1, lp: 0, co: 0 };

const arr = [];

for (const key in obj) {
  if (obj[key] === 1) arr.push(key);
}

console.log(arr);
英文:

That's an object. Iterate over the object and push the property key into an array if its corresponding value equals 1.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const obj = { tp: 1, op: 1, lp: 0, co: 0 };

const arr = [];

for (const key in obj) {
  if (obj[key] === 1) arr.push(key);
}

console.log(arr);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月7日 01:53:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定