skip to Main Content

I have one array object and one array. what are the values in that array that value matched in the array object need to change the status like true.

arrObj output should be like below:

[
    { name: "Test1", status: true }, 
    { name: "Test2", status: false }, 
    { name: "Test3", status: true }
]

Demo: https://stackblitz.com/edit/github-7plax5-mu3l6a?file=src%2Fapp%2Fapp.component.ts

let arrObj = [{
    name: "Test1",
    status: false
  },
  {
    name: "Test2",
    status: false
  },
  {
    name: "Test3",
    status: false
  }
]

let arr = ["Test1", "Test3"];

for (k of arr) {
  if (arrObj.name == k) {
    arrObj.status = true;
  }
}

console.log(arrObj);

3

Answers


  1. The function updateStatus is now defined, which makes the code more readable and reusable.
    The for loop in updateStatus is now using the forEach method, which is a more efficient way to iterate through an array.
    The if statement in updateStatus is now using the === operator, which is more accurate than the == operator.

    const arrObj = [
      {
        name: "Test1",
        status: false
      },
      {
        name: "Test2",
        status: false
      },
      {
        name: "Test3",
        status: false
      }
    ];
    
    const arr = ["Test1", "Test3"];
    
    const updateStatus = (arrObj, arr) => {
      for (const obj of arrObj) {
        for (const name of arr) {
          if (obj.name === name) {
            obj.status = true;
          }
        }
      }
    
      return arrObj;
    };
    
    const result = updateStatus(arrObj, arr);
    
    console.log(result);
    
    Login or Signup to reply.
  2. You are iterating wrong array,
    iterate arrObj and then check if array contains that value using the indexOf method

        let arrObj = [
          {
          name:"Test1",
          status:false
          }, 
          {
          name:"Test2",
          status:false
          },
          {
          name:"Test3",
          status:false
          }
          ]
          
          let arr= ["Test1","Test3"];
          
          arrObj.forEach(function(k){
             if(arr.indexOf(k.name)!=-1){
                 k.status = true;
          }
          });
    
    
          console.log(arrObj)
    Login or Signup to reply.
  3. Simplest method to modify the original array

    arrObj.forEach(item => item.status = arr.includes(item.name))
    
    console.log(arrObj);
    <script>
    let arrObj = [{
        name: "Test1",
        status: false
      },
      {
        name: "Test2",
        status: false
      },
      {
        name: "Test3",
        status: false
      }
    ]
    
    let arr = ["Test1", "Test3"];
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search