从基于值的对象数组中形成对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从基于值的对象数组中形成对象相关的知识,希望对你有一定的参考价值。
需要搜索对象数组并基于值'X'和'AND'/ OR形成对象。尝试以下代码,但无法继续
输入:
let objArr = [ "L1":"NA","L2":"X","L1L2":"NA","L3":"NA","L1":"X","L2":"NA","L1L2":"AND","L3":"NA" ]
输出:
Obj = "L1":"X","L2":"X","L1L2":"AND","L3":"NA"
代码:
Object.keys(objArr ).forEach((key) =>
if (!(temp[key] == "X" || temp[key] == "AND" || temp[key] == "OR"))
temp[key] = objArr [key]
)
答案
您可以通过检查获得键并映射条目并创建一个新对象。
let array = [
L1: "NA", L2: "X", L1L2: "NA", L3: "NA" ,
L1: "X", L2: "NA", L1L2: "AND", L3: "NA"
],
prime = ['X', 'AND', 'OR'],
result = array.reduce((a, b) => Object.fromEntries(Object
.keys(a)
.map(k => [k, prime.includes(b[k]) ? b[k] : a[k]])
));
console.log(result);
另一答案
您可以使用reduce
方法,并在for...of
上进行一个Object.entries
循环。
let objArr = [ "L1":"NA","L2":"X","L1L2":"NA","L3":"NA","L1":"X","L2":"NA","L1L2":"AND","L3":"NA" ]
let result = objArr.reduce((r, e) =>
for (let [k, v] of Object.entries(e))
r[k] = (!r[k] || r[k] == 'NA') ? v : r[k]
return r;
, );
console.log(result)
以上是关于从基于值的对象数组中形成对象的主要内容,如果未能解决你的问题,请参考以下文章
Angular - 我正在尝试从数组对象值的下拉菜单中填充和选择