嵌套字典到字符串列表-TypeScript [英] Nested dictionary to list of strings - typeScript

查看:410
本文介绍了嵌套字典到字符串列表-TypeScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的字典,我想将其转换为字符串列表.例如我有这个输入:

I have a nested dictionary which I want to convert to a list of strings. e.g. I have this input:

var group = {
    '5': {
        '1': {
            '1': [1,2,3],
            '2': [1]
        },
        '2':{
            '1': [2,4],
            '2': [1]
        }
    },
    '1': {
        '1':{
            '1':[1,2,5],
            '2':[1]
        },
        '2':{
            '1':[2,3]
        }
    }
};

我想要这个输出:

a = ["5.1.1.1","5.1.1.2","5.1.1.3"..... "1.2.1.3"]

我从这个递归函数开始:

I started with this recursive function:

function printValues(obj) {
    for (var key in obj) {
    console.log(key)
        if (typeof obj[key] === "object") {
            printValues(obj[key]);   
        } else {
            console.log(obj[key]);    
        }
    }
}

但是t还行不通..

推荐答案

您可以采用迭代和递归的方法,首先获取嵌套最多的项,然后构建所需的字符串.

You could take an iterative and recursive approach and get the most nested items first and build the wanted strings.

它如何工作?

它从对象中获取所有条目(键/值对),并将展开的数组推入结果集中.

It takes from an object all entries (key/value pairs) and pushes a spreaded array to the result set.

要传播的数组是

  • 一个值数组或

  • an array of values or

以对象 v 作为参数再次调用该函数的数组

an array from calling the function again with the object v as parameter

通过从对象中获取键 k 和从数组中获取项以获取所需样式 n.m 来映射两个数组.

Both arrays are mapped by taking the key k from the object and an item from the array for getting the wanted style n.m.

例如,使用一个子 {1:[2,4],2:[1]} 对象并获取一个键/值数组.

For example take a sub { 1: [2, 4], 2: [1] } object and get an array of key/values.

[
    [1, [2, 4]],
    [2, [1]]
]

这是 reduce 的第一次迭代的结果.该顺序是从内部进行的逻辑运算:

This is the result of the first iteration of reduce. The order is the logical run from the inside:

  1. 是的,这是一个数组,
  2. v [2,4]
  3. 将此值与 k 1
  4. 一起映射
  5. 获取 ['1.2','1.4']
  6. 的数组
  7. 展开此数组,然后
  8. 将每个元素作为参数.

然后执行第二个循环并获得 ['1.2','1.4','2.1'] .该结果作为 getPathes 中的值,并与每个字符串前面的实际键进行映射.

Then take the second loop and get ['1.2', '1.4', '2.1']. This result is taken as value from getPathes and mapped with the actual key in front of each string.

结果是由深度优先搜索构建的,以获取最大的收益内部数组并将键放在每个项目的前面.

The result is a build by a depth-first search for getting the most inner array and put the key in front of each item.

function getPathes(object) {
    return Object.entries(object).reduce((r, [k, v]) => {
        r.push(...(Array.isArray(v) ? v : getPathes(v)).map(l => `${k}.${l}`));
        return r;
    }, []);
}

var group = { 5: { 1: { 1: [1, 2, 3], 2: [1] }, 2: { 1: [2, 4], 2: [1] } }, 1: { 1: { 1: [1, 2, 5], 2: [1] }, 2: { 1: [2, 3] } } },
    result = getPathes(group);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于嵌套字典到字符串列表-TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆