简体   繁体   English

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

[英]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? 如何用dataNumbers中的值替换data中的0,1,2?

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? 如何用dataNumbers替换数据中的数字?

After replacement, 更换后,

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

Trying to achieve something like this? 试图实现这样的目标?

 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); 

Do you want something like this: 您想要这样的东西吗?

 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); 

You can use the map() function for both of these cases. 对于这两种情况,都可以使用map()函数。

 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); 

You could iterate the target array and assign the value of source array at the same index. 您可以迭代目标数组,并在同一索引处分配源数组的值。

 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); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM