[英]Javascript, how to add an object to an array, if some properties of this object dont already exist in the array
I have the following array (name is always random)我有以下数组(名称总是随机的)
array =
[
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
ventasAnuales: "ventasAnuales",
slActive: true
},
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
ventasAnuales: "ventasAnuales",
slActive: true
},
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
ventasAnuales: "ventasAnuales",
slActive: true
},
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
empleados: "empleados",
slActive: true
}
]
Now I want to add extrao objects to the array, and I do it with a concat现在我想在数组中添加额外的对象,我用一个 concat 来做
array.concat(a).filter(i => i.active)
Problem is that there are certains conditions I should look for before doing the concat.问题是在进行连接之前我应该寻找某些条件。 Like for example
比如像
ventasAnuales | empleados
ventasAnuales | empleados
ventasAnuales | empleados
already exists in the array, but field3 is different. ventasAnuales | empleados
已经存在于数组中,但 field3 不同。 It should replace itFor example, given that I want to add the following object例如,假设我要添加以下 object
{
active: true,
field1: "100",
field2: "",
field3: "2",
name: 0.0020423,
ventasAnuales: "ventasAnuales",
slActive: true
},
It would replace the first element of the array它将替换数组的第一个元素
ventasAnuales | empleados
ventasAnuales | empleados
ventasAnuales | empleados
and the field1 is different, it should be replaced by the new object. ventasAnuales | empleados
和field1不同,应该换成新的object。 For example, given that i want to add the following object.例如,假设我想添加以下 object。
{
active: true,
field1: "50",
field2: "",
field3: "1",
name: 0.1020123,
ventasAnuales: "ventasAnuales",
slActive: true
}
It should end up replacing the first element of the array.它最终应该替换数组的第一个元素。
How should i write my concat to make this work?我应该如何编写我的 concat 来完成这项工作?
Just filter the array to find any items that should prevent from insertion.只需过滤数组以查找应阻止插入的任何项目。 In case you do not find any, add the new item.
如果您没有找到,请添加新项目。
you can use [].filter()
like so:您可以像这样使用
[].filter()
:
const items = […, …, …]
const containing = items.filter(item => item.active == true);
if (containing.length == 0) items.push( … )
but [].every()
or [].some()
may do as well.但是
[].every()
或[].some()
也可以。
Example with every()
every()
的示例
if ( !items.every( i => !i.active ))
items.push({ active: false })
In case you need to replace an existing element you can use findIndex()
like so:如果您需要替换现有元素,您可以像这样使用
findIndex()
:
const items = […, …, …];
const idx = items.findIndex(itm => itm.active);
// create a new item
if (idx < 0) {
items.push(…)
}
else {
// update
items[idx] = …
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.