wizard23 wizard23 - 7 months ago 37
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,


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

After replacement,


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;

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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download