wizard23 wizard23 - 29 days ago 10
Javascript Question

Javascript - Replace items in array/object with new items

There are two arrays.

data = [["hi","0"],["hello","1"],["world","2"]]

dataNumbers = ["0","2","1"]


How can I replace the 0,1,2 in data with the values in dataNumbers?

After replacement,

data = [["hi","0"],["hello","2"],["world","1"]]


And in here,

{"data":[["hi","0"],["hello","1"],["world","2"]],"dataNumbers":["0","2","1"]}


How do I replace them the numbers in data with dataNumbers?

After replacement,

{"data":[["hi","0"],["hello","2"],["world","1"]],"dataNumbers":["0","2","1"]}

Answer Source

You can use the map() function for both of these cases.

let data = [["hi","0"],["hello","1"],["world","2"]];
let dataNumbers = ["0","2","1"];

let newData = data.map(function(item,index){
  item[1] = dataNumbers[index];
  return item;
  });
console.log(newData);

let obj = {"data":[["hi","0"],["hello","1"],["world","2"]],"dataNumbers":["0","2","1"]};
obj.data = obj.data.map(function(item,index){
  item[1] = obj.dataNumbers[index];
  return item;
  });
  console.log(obj);