搜索

首页  >  问答  >  正文

如何更改数组对象属性值javascript

<p>我有一个数组对象和一个数组。该数组中的哪些值与数组对象中的值匹配需要更改状态(如 true)。</p> <p><code>arrObj</code> 输出应如下所示:</p> <pre class="brush:php;toolbar:false;">[ { name: "Test1", status: true }, { name: "Test2", status: false }, { name: "Test3", status: true } ]</pre> <p>演示:https://stackblitz.com/edit/github-7plax5-mu3l6a?file=src%2Fapp%2Fapp.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粉618358260457 天前357

全部回复(1)我来回复

  • P粉412533525

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

    修改原始数组的最简单方法

    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 版本 运行与我已经发布的脚本相同的脚本推断的类型

    回复
    0
  • 取消回复