Home > other >  Update an array based on the value of object
Update an array based on the value of object

Time:12-22

Iam having an array of object named finalArr and and object named replaceJsonData. If replaceJsonData contains add =1 , then value of REQUEST_TYPE in finalArr should also become 1

finalArr = [{
  REQUEST_TYPE: 'add',
  TIMESTAMP: '1671636661867',
}, ]

let replaceJsonData = {
  "REQUEST_TYPE": {
    'add': 1,
    'modify': 2
  }
}

I tried like this way , but value itself is in the form a key

finalArr.map((ele)=>{
    Object.entries(replaceJsonData ).forEach(
        ([replaceDataKey, replaceDataValue]) => {
          if (ele[replaceDataKey]) {
            ele[replaceDataKey]=replaceDataValue
         }
       }
     )
});

Expected Output:

finalArr = [{
  REQUEST_TYPE: 1,
  TIMESTAMP: '1671636661867',
}, ]

CodePudding user response:

Use the property of replaceDataValue that matches the old value of the property being updated: replaceDataValue[ele[replaceDataKey]]

let finalArr = [{
  REQUEST_TYPE: 'add',
  TIMESTAMP: '1671636661867',
}, ]

let replaceJsonData = {
  "REQUEST_TYPE": {
    'add': 1,
    'modify': 2
  }
};

finalArr.map((ele) => {
  Object.entries(replaceJsonData).forEach(
    ([replaceDataKey, replaceDataValue]) => {
      if (ele[replaceDataKey]) {
        ele[replaceDataKey] = replaceDataValue[ele[replaceDataKey]];
      }
    }
  )
});

console.log(finalArr);

  • Related