Javascript 将数组对生成键索引列表

标签 javascript arrays json indexing

enter image description here

我有如下所示的数组对列表:

0: [0, "535222325"]
1: [1, "346362534"]
2: [0, "534534646"]
3: [1, "745354367"]
    ^ <--- Index for array where to append value

我如何通过索引键的第一个值将其转换为如下所示的列表

0: ["535222325","534534646"]
1: ["346362534","745354367"]
^ <--- Unique index found from array above

或者当在for循环中找到具有匹配索引的值时如何追加到键中

我的脚本示例:

for(var u = 0; u < Object.keys(freshData).length; u++) {
    tag[u].Index <-- This I want to use as a key, whenever new unique match appears
    tag[u].Value <-- This I want to add in to array of that key
} 

对于非常糟糕的解释,我们深表歉意。 Target 只是通过唯一键创建列表,这些键在 for 循环中找到。

最佳答案

Array.prototype.reduce 拯救:

const data = [
  [0, "535222325"],
  [1, "346362534"],
  [0, "534534646"],
  [1, "745354367"]
]

const groupKVPairs = (pairs, container = {}) => pairs.reduce(
  (acc, [key, value]) => {
    const group = acc[key]
    if (group !== undefined) group.push(value)
    else acc[key] = [value]
    return acc
  },
  container
)

console.log(groupKVPairs(data, []))
// output -> [["535222325", "534534646"], ["346362534", "745354367"]]

console.log(groupKVPairs(data, {}))
// output -> { "0": ["535222325", "534534646"], "1": ["346362534", "745354367"]}

console.log(groupKVPairs(data))
// output -> { "0": ["535222325", "534534646"], "1": ["346362534", "745354367"]}

关于Javascript 将数组对生成键索引列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469322/

相关文章:

javascript - 在 Vanilla JavaScript 中,当有多个模型/ View / Controller 时,我该如何构建我的应用程序?

mysql - 如何从 MySQL JSON 数组中选择行?

崩溃没有错误,排序算法

php - 无法将 swift 应用程序连接到 MySQL

java - 将 JSON 反序列化为 transient 字段

javascript - 我的 React 应用程序出现错误 "action undefined"

java - GPS 设备和编程

javascript - Point-n-Click JQuery 选择器生成器?

javascript - 将值列表作为可过滤内容传递

json - 松弛API chat.update返回 'not_authed'错误