重构嵌套对象 [英] Restructure nested Object

查看:37
本文介绍了重构嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.我有一个具有这种结构的对象,就像这个例子一样.

I have a problem. I have an object with this structure like this example.

{
    "Name": "Peter",
    "Username": "dummy",
    "Age": 18,
    "moreData": {
        "tags": [1,2,3],
        "hasCar": true,
        "preferences": {
            "colors": ["green", "blue"]
        }
    }
}

我想将其转换为如下所示的数组.我很绝望,不能再进一步了.一旦我得到一些嵌套对象,我就会遇到问题.有人知道我如何实现这一目标吗?亲切的问候

I would like to convert it to an array like the following. I am desperate and can not get any further. I have issues as soon I get some nested objects. Does someone have an idea how I can achieve this? Kind Regards

[
    {
        "key": "Name",
        "val": "Peter"
    },
    {
        "key": "Username",
        "val": "dummy"
    },
    {
        "key": "Age",
        "val": "18"
    },
    {
        "key": "tags",
        "val": [1,2,3]
    },
    {
        "key": "hasCar",
        "val": true
    },
    {
        "key": "colors",
        "val": ["green", "blue"]
    }
]

推荐答案

为此,您需要首先遍历对象的所有键值对,并将特定类型的数据更改为除嵌套对象之外的名称值对.如果某个键的对象中的值是一个对象,则必须对其执行相同的过程.由于这个嵌套数据可以有 N 个级别,因此我们需要一个递归函数.每当我们必须对嵌套数据进行相同的处理时,这总是意味着可以使用递归来完成.也可以通过 for 循环来完成,但递归函数更清晰,更难写.

For this you need to first iterate through all the key value pairs of your object and change the specific type of data into name value pairs except the nested objects. If the value in the object at a certain key is an object then the same procedure has to be done for it. And since there can be N number of levels for this nested data thus we need a recursive function for it. Whenever we have to do a same set of processing for nested data then it always means it can be done using recursion. It can be done via for loops too but a recursive function is much clear and lesser to write.

function getData(data) {
 let results = [];
 Object.keys(data).forEach(key => {
   // If the type of the data item is object and is not an array, go into recursion
   if(typeof data[key] == 'object' && !Array.isArray(data[key])) {
      results = results.concat(getData(data[key]));
   } else {
      results.push({ key, val: data[key] });
   }
 });
 return results;
}

const data = {
  "Name": "Peter",
  "Username": "dummy",
  "Age": 18,
  "moreData": {
    "tags": [1,2,3],
    "hasCar": true,
    "preferences": {
        "colors": ["green", "blue"]
    }
  }
};

const results = getData(data);
console.log(results);
// [{"key":"Name","val":"Peter"},{"key":"Username","val":"dummy"},{"key":"Age","val":18},{"key":"tags","val":[1,2,3]},{"key":"hasCar","val":true},{"key":"colors","val":["green","blue"]}]

这篇关于重构嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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