H4z4
H4z4

Reputation: 23

Replace an empty values in Array of Objects with the previous filled values

I have an array of objects and some values of the object are empty and I want to replace them with the values of the previous object, here is an example :

[
  {
    name: "Mark",
    surname: "Something",
  },
  {
    name: "",
    surname: "",
  },
  {
    name: "Richard",
    surname: "SomeSurname",
  },
  {
    name: "",
    surname: "",
  },
];

my goal is to replace the empty value with previous ones like that :

[
  {
    name: "Mark",
    surname: "Something",
  },
  {
    name: "Mark",
    surname: "Something",
  },
  {
    name: "Richard",
    surname: "SomeSurname",
  },
  {
    name: "Richard",
    surname: "SomeSurname",
  },
];

Upvotes: 1

Views: 942

Answers (3)

androidoverlord
androidoverlord

Reputation: 301

const array = [
  {
    name: "Mark",
    surname: "Something",
  },
  {
    name: "",
    surname: "",
  },
  {
    name: "Richard",
    surname: "SomeSurname",
  },
  {
    name: "",
    surname: "",
  },
];

//create new array with map es6
let newArray = array.map( (obj,index) => { 
  if( !obj.name && !obj.surname ){
    //if values are empty, create a new one with the previous index
    return { name: array[index-1].name, surname: array[index-1].surname }
  }
  //else return original value
  return obj
})

console.log( newArray );

Upvotes: 1

Mureinik
Mureinik

Reputation: 311188

I'd run over the list and save the index of the last non-empty object os far, and then update the values to it when I encounter an empty one:

const list = [
  {
    name: "Mark",
    surname: "Something",
  },
  {
    name: "",
    surname: "",
  },
  {
    name: "Richard",
    surname: "SomeSurname",
  },
  {
    name: "",
    surname: "",
  },
];

let emptyIndex = 0;
for (let i = 0; i < list.length; ++i) {
  if (list[i].name) {
    fullIndex = i;
  } else {
    list[i].name = list[fullIndex].name;
    list[i].surname = list[fullIndex].surname;
  }
}

console.log(list);

Upvotes: 1

kol
kol

Reputation: 28688

const a = [
  {
    name: "Mark",
    surname: "Something"
  },{
    name: "",
    surname: "" 
  },{
    name: "Richard",
    surname: "SomeSurname"
  },{
    name: "",
    surname: ""
  }
];
for (let i = 0; i < Math.trunc(a.length / 2); ++i) {
  a[2 * i + 1].name = a[2 * i].name;
  a[2 * i + 1].surname = a[2 * i].surname;
}
console.log(a);

Upvotes: 0

Related Questions