从基于值的对象数组中形成对象

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 - 我正在尝试从数组对象值的下拉菜单中填充和选择

从 JavaScript 数组中获取对象值的最大值和最小值

如何从对象数组中获取具有属性的列表,除非它包含具有特定值的另一个项目?

从数组中过滤对象,具有匹配两个值的差异

数组对象修改某一个属性值的数据类型

使用 TypeScript 从数组中删除具有特定 id 字段值的对象的聪明方法是啥? [复制]