Home  >  Q&A  >  body text

JavaScript add array to existing array of objects

<p>我有下面的代码片段</p> <p> <pre class="brush:js;toolbar:false;">const arr = [ { "name": "Attestation Component 1", "values": [ { "component": "Attestation Component 1" }, { "component": "Attestation Component 1" }, { "component": "Attestation Component 1", } ] }, { "name": "Attestation Component 2", "values": [ { "id": "10005884", "url": "https://www.msn.com", "bfaId": "G44.5.3.1N/A", "component": "Attestation Component 2" }, { "id": "10005883", "url": "https://www.hotmail.com", "bfaId": "G44.5.3.2N/A", "component": "Attestation Component 2" } ] }, { "name": "Attestation Component 3", "values": [ { "id": "10005882", "url": "https://www.rediffmail.com", "bfaId": "G44.5.3.3N/A", "component": "Attestation Component 3" } ] } ] const bool = arr.map(group => group.values.every(val => val.id)); console.log(bool);</pre> </p> <p>我有三个对象,名称分别为证明组件 1、证明组件 2、证明组件 3。我得到的预期输出为 false、true、true。这是什么原因呢?我想将该属性添加到现有对象数组中,作为 <code>name</code></p> 下方的 <code>isInvalid: true/false</code> <p>预期的 O/P(在每个具有以下键值对的对象中添加属性) <code>isInvalid:真/假</code></p>
P粉556159786P粉556159786411 days ago436

reply all(2)I'll reply

  • P粉619896145

    P粉6198961452023-09-05 10:42:18

    You should use some(), not every().

    const bool = arr.map(group => group.values.some(val => val.id)).filter(bool => !bool).toString();

    every() method is used to check whether all elements in the array meet the given conditions. array. The some() method is used to check whether at least one element in the array meets the given condition.

    reply
    0
  • P粉336536706

    P粉3365367062023-09-05 10:07:13

    That's because your algorithm is incorrect. The every method will check if all objects have an id, but that's not what you want, right?

    So try this

    const bool = arr.map(group => group.values.some(val => val.id));

    reply
    0
  • Cancelreply