简体   繁体   English

JS比较和修改数组中的嵌套数组项

[英]JS comparing and modifying nested array items inside array

What is the correct / best practice way to perform the following?执行以下操作的正确/最佳实践方法是什么?

I have an array that contains a dynamic number of arrays within it.我有一个数组,其中包含一个动态数字 arrays。 Each nested array is built like so: (the values change obviously)每个嵌套数组都是这样构建的:(值明显变化)

["100",{"value":"0.10","amount":"6000"}]

In some of the nested arrays, the first item ("100" in the example) repeats itself.在一些嵌套的 arrays 中,第一项(示例中的“100”)重复了自己。 In such case, I would like to add the second item (the key-value pairs) to the nested array.在这种情况下,我想将第二项(键值对)添加到嵌套数组中。

Example:例子:

Original Array-原阵-

[
["631",{"value":"0.10","amount":"6000"}],
["100",{"value":"0.20","amount":"5000"}],
["631",{"value":"0.30","amount":"7000"}]
]

Desired Output-期望的输出-

[
["631",{"value":"0.10","amount":"6000"}, {"value":"0.30","amount":"7000"}],
["100",{"value":"0.20","amount":"5000"}]
]

I've thought about iterating through the original array and then performing an if comparison but couldn't reach the exact desired output format.我考虑过遍历原始数组然后执行 if 比较但无法达到所需的确切 output 格式。 Any help?有什么帮助吗? Thanks in advance.提前致谢。

I did use one for and one conditional if我确实使用了一个for和一个条件if

 data = [ ["631",{"value":"0.10","amount":"6000"}], ["100",{"value":"0.20","amount":"5000"}], ["631",{"value":"0.30","amount":"7000"}] ] result = []; for (key in data) { var index =result.findIndex((item) => item[0] === data[key][0]) if(index<0){ result.push(data[key]) } else { result[index].push(data[key][1]) } } console.log(result)

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

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