Update field of a selection of an object array with filter

Asked

Viewed 874 times

0

I have a selected list with some records (not all) and I need to apply an update in specific field of the selection but I don’t want to repeat arr.filter(x).filter(y).filter(z...)

In a normal situation of just one record I do so in Vue:

const obj = { 'id': 1, 'b': 2, 'c': false }

const resultado = {...obj, c: true}

and through an actions call a Mutation that updates the store:

export const ATUALIZAR_LOG = (state, resultado) => {

  const indice = state.logs.findIndex(c => c.id === resultado.id)
  state.logs.splice(indice, 1, resultado)
}

But now I need to update a selection of an array:

const array = [  
    { 'id': 1, 'b': 2, 'c': false },  
    { 'id': 2, 'b': 2, 'c': false },  
    { 'id': 3, 'b': 2, 'c': false },  
    { 'id': 4, 'b': 2, 'c': false },  
    { 'id': 5, 'b': 2, 'c': false }  
]

I need to update the c field with true of the Ids (2 and 4) so when the client selects Ids 2 and 4 from a list I get an array:

let selecao = [2, 4] // resultado da seleção do cliente const campo = { 'c': true } // campo que eu vou atualizar

If I play the ID directly in the filter until I get example:

let campo = { 'c': true }  
const resultado = array.filter(i => i.id === 3).map(o => Object.assign(o, campo))

or even calling a function:

function filtroChave (chave) {  
    if (chave.id === 2 || chave.id === 4 || ...) {  
        return true  
    }  
    return false  

}  

let campo = { 'c': true }  
const resultado = array.filter(filtroChave).map(o => Object.assign(o, campo))  

The expected result I get but, I do not want to release static until pq I do not know how many records the user will choose besides looking horrible to see.

I don’t like the For* of life but I even tried a forIn without success.
I have no idea how to have this result and even having this result do not know how to update vueX

1 answer

0


Uses the reduce and creates a new array.

See if it helps:

const array = [
{ 'id': 1, 'b': 2, 'c': false },
{ 'id': 2, 'b': 2, 'c': false },
{ 'id': 3, 'b': 2, 'c': false },
{ 'id': 4, 'b': 2, 'c': false },
{ 'id': 5, 'b': 2, 'c': false }
];

let ids = [2, 4];

let result = array.reduce((acc, o) => acc.concat(ids.includes(o.id) ? Object.assign(o, { c: true }) : o), []);

console.log(result);

// ou
let result2 = array.reduce((acc, o) => {

    let obj = ids.includes(o.id) ? Object.assign(o, { c: true }) : o;

    acc.push(obj);

    return acc;

}, []);

  • The problem is that I get a matrix type [1, 5, 7, 11.... ], I do not have a key to identify moreover I can not make mutation directly in the matrix because vueX complains.

  • @sidiaracastro I edited the answer

  • Show my friend! I made a small change to meet my need and is working yes as expected. Thank you so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.