JavaScript add array to existing array of objects
P粉556159786
2023-09-04 11:46:33
<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>
You should use some(), not every().
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.
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