Javascript - 用新项替换数组/对象中的项

时间:2017-08-22 16:28:45

标签: javascript

有两个阵列。

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

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

如何用dataNumbers中的值替换数据中的0,1,2?

更换后,

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

在这里,

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

如何用dataNumbers替换数据中的数字?

更换后,

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

4 个答案:

答案 0 :(得分:0)

尝试实现这样的目标?

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

const IDX_DESIRED_NUM = 1;

for (var i = 0; i < data.length; i++) {
  data[i][IDX_DESIRED_NUM] = dataNumbers[i];
}

console.log(data);

答案 1 :(得分:0)

你想要这样的东西:

&#13;
&#13;
var data = [["hi","0"],["hello","1"],["world","2"]];

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

for(var i=0;i<data.length;i++){

  data[i][1]=dataNumbers;
  
}

console.log(data);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

对于这两种情况,您都可以使用map()功能。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以迭代目标数组并在同一索引处分配源数组的值。

&#13;
&#13;
var object = { data: [["hi", "0"], ["hello", "1"], ["world", "2"]], dataNumbers: ["0", "2", "1"] };

object.data.forEach((a, i) => a[1] = object.dataNumbers[i]);

console.log(object);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;