简体   繁体   中英

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

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

  1. If an object with equal field1 and has the same last but one property ventasAnuales | empleados ventasAnuales | empleados already exists in the array, but field3 is different. It should replace it

For example, given that I want to add the following object

{
active: true,
field1: "100",
field2: "",
field3: "2",
name: 0.0020423,
ventasAnuales: "ventasAnuales",
slActive: true
},

It would replace the first element of the array

  1. If i add an object with the same field3 value, the same last but one property ventasAnuales | empleados ventasAnuales | empleados and the field1 is different, it should be replaced by the new object.

For example, given that i want to add the following 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?

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:

const items = […, …, …]
const containing = items.filter(item => item.active == true);
if (containing.length == 0) items.push( … )

but [].every() or [].some() may do as well.

Example with 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:

const items = […, …, …];
const idx = items.findIndex(itm => itm.active);


// create a new item
if (idx < 0) {
  items.push(…)
}
else {
  // update
  items[idx] = …
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM