How to change a specific object into an object array?

Asked

Viewed 81 times

0

I have an object array that’s coming from my API that I’m saving on state

const state = {
    books: [{name: "Maria", age:"22"},{name:"Roberto", age:20}]
}

how to change Roberto’s age in this case? what would be the ways to do this?

3 answers

3

  • and if I want to change age and name?

  • vc would just have to do the "checks" on "x" object filtering by its properties

1

You first need to "find" the Obert in your 'base', then you can change its age, see:

const state = {
    books: [{name: "Maria", age:"22"},{name:"Roberto", age:20}]
};

robertos = state.books.filter(function (obj){ return obj.name === 'Roberto'});
if (robertos.length>0){
    robertos[0].age = "40"
};
console.log(state);

EDIT:

buscaNomeEAltera = function (nome, novos_dados){
    buscados = state.books.filter(function (obj){ return obj.name === nome});
    if (buscados.length===1){
        buscados[0] = Object.assign(buscados[0], novos_dados)
    };
};
buscaNomeEAltera('Roberto', {name: 'João', age: 20});
  • how would I generalize? for example if I wanted to change several attributes?

  • You would have to further sophisticate the solution, creating a function (for example) that would receive the name you are looking for and the object with the new values and doing one of the objects like this: obj2 = Object.assign(robertos[0], {nome: 'James', idade: 28})

1


I researched my case and I managed to find an ideal way to solve, I left comments in the code to help explain.

const state = {
    books: [{name: "Maria", age:"22"},{name:"Roberto", age:20}]
}

const data = {
    name: "Roberto Silva",
    age: 34
}
// acha o index do objeto especifico
const objIndex = state.books.findIndex(objs => objs.name === "Roberto");
// agora o objeto recebe as alteraçõs recebidas
const updatedObj = { ...this.capitulos[objIndex], ...data };
// nessa etapa irei fazer a reconstrução do objeto
// eu pego todos os objetos do 0 até o index do objeto modificado
// depois coloco o objeto modificado
// e pra finalizar pego todos os objetos a partir do objeto modificado ate o final
const updatedBooks = [
    ...state.books.slice(0, objIndex), 
    updatedObj, 
    ...state.books.slice(objIndex + 1)
];
// agora o books vai receber o novo estado
state.books = updatedBooks;

Documentation of the functions used

Browser other questions tagged

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