Home  >  Q&A  >  body text

How to change array object property value javascript

<p>I have an array object and an array. Which values ​​in this array match values ​​in the array object require a change of state (such as true). </p> <p><code>arrObj</code> The output should look like this: </p> <pre class="brush:php;toolbar:false;">[ { name: "Test1", status: true }, { name: "Test2", status: false }, { name: "Test3", status: true } ]</pre> <p>Demo: https://stackblitz.com/edit/github-7plax5-mu3l6a?file=src/app/app.component.ts</p> <p> <pre class="snippet-code-js lang-js prettyprint-override"><code>let arrObj = [{ name: "Test1", status: true }, { name: "Test2", status: true }, { name: "Test3", status: true } ] let arr = ["Test1", "Test3"]; for (k of arr) { if (arrObj.name == k) { arrObj.status = true; } } console.log(arrObj);</code></pre> </p>
P粉618358260P粉618358260412 days ago329

reply all(1)I'll reply

  • P粉412533525

    P粉4125335252023-09-04 10:47:27

    The simplest way 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>

    Typescript Version Types inferred by running the same script as the one I have posted

    reply
    0
  • Cancelreply