2

Need to search objects array and form an object based on the value 'X' and 'AND'/OR. Tried with below code but couldnt proceed

Input :

 let objArr = [ {"L1":"NA","L2":"X","L1L2":"NA","L3":"NA"},{"L1":"X","L2":"NA","L1L2":"AND","L3":"NA"} ]

Output:

Obj = {"L1":"X","L2":"X","L1L2":"AND","L3":"NA"}          

Code:

 Object.keys(objArr ).forEach((key) => {
      if (!(temp[key] == "X" || temp[key] == "AND" || temp[key] == "OR")) {
        temp[key] = objArr [key]
      }
    })

2 Answers 2

1

You could get the keys and map the entries after a check and create a new object.

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);

Sign up to request clarification or add additional context in comments.

Comments

1

You could do this using reduce method and one for...of loop inside it on 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.