英文:
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的键(名称),你可以使用以下代码:
- 转换为条目数组
- 按值筛选
- 提取名称
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:
- Convert to an array of entries
- Filter by value
- 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]) => value === 1)
.map(([name]) => 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 -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论