gpt4 book ai didi

javascript - 在 JS 中映射对象

转载 作者:行者123 更新时间:2023-11-30 19:07:29 25 4
gpt4 key购买 nike

我有一个这样的对象;

{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":"","7":"","8":"","9":6,"10":7,"11":"","12":8,"13":9,"14":10}

或者最初是一个数组:

[{"id":0,"tag":0},{"id":1,"tag":1},{"id":2,"tag":2},{"id":3,"tag":3},{"id":4,"tag":4},{"id":5,"tag":5},{"id":6,"tag":""},{"id":7,"tag":""},{"id":8,"tag":""},{"id":9,"tag":6},{"id":10,"tag":7},{"id":11,"tag":""},{"id":12,"tag":8},{"id":13,"tag":9},{"id":14,"tag":10}]

最后,我想检索一个相同的对象,但只有 key:value 且 value 不是 = 为零。

喜欢:

{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"9":6,"10":7,"12":8,"13":9,"14":10}

最佳答案

只需过滤具有虚假tag属性的对象(0和空字符串是虚假的):

let results = arr.filter(o => o.tag);

例子:

let arr = [{"id":0,"tag":0},{"id":1,"tag":1},{"id":2,"tag":2},{"id":3,"tag":3},{"id":4,"tag":4},{"id":5,"tag":5},{"id":6,"tag":""},{"id":7,"tag":""},{"id":8,"tag":""},{"id":9,"tag":6},{"id":10,"tag":7},{"id":11,"tag":""},{"id":12,"tag":8},{"id":13,"tag":9},{"id":14,"tag":10}];


let results = arr.filter(o => o.tag);

console.log(results);

如果 tag 可能有其他您想保留的虚假值(例如 falsenull),则将过滤条件更改为更明确的一个:

let results = arr.filter(o => o.tag !== 0 && o.tag !== "");

例子:

let arr = [{"id":0,"tag":0},{"id":1,"tag":false},{"id":2,"tag":2},{"id":3,"tag":3},{"id":4,"tag":4},{"id":5,"tag":5},{"id":6,"tag":""},{"id":7,"tag":""},{"id":8,"tag":""},{"id":9,"tag":6},{"id":10,"tag":null},{"id":11,"tag":""},{"id":12,"tag":8},{"id":13,"tag":9},{"id":14,"tag":10}];


let results = arr.filter(o => o.tag !== 0 && o.tag !== "");

console.log(results);

关于javascript - 在 JS 中映射对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58840495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com