Javascript:将嵌套 JSON 转换为简单 JSON 💎 很高兴看到您的回复

2025-05-28

Javascript:将嵌套 JSON 转换为简单 JSON

💎 很高兴看到你的回复

这将是我们几乎经常使用的实用功能。

根据数据的种类和结构,API 响应可能会返回非常复杂的 JSON。有时,仅从整个 JSON 中捕获一个字段是不够的。我们可能需要在网页上显示多个字段。每次都遍历如此复杂的 JSON 并非明智之举。如果我们能根据具体情况将其转换为简单的 JSON,效果会更好。

希望介绍够了。接下来我们进入正题。

这里,我采用了多层嵌套的 JSON。我会将其转换为简单的 JSON。

以下是我的示例 JSON:

const obj = {
    first: {
        first: '1',
        second: {
            second: true,
            third: {
                third: 'third',
                fourth: {
                    fourth: 4
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

我想要的输出是:

{first: '1', second: true, third: 'third', fourth: 4}
Enter fullscreen mode Exit fullscreen mode

再次查看输入和输出以获得想法。

让我们编写一些代码来实现上述目标:

const simpleObj = {};
function destructure(obj) {
    for (let key in obj) {
        const value = obj[key];
        const type = typeof value;
        if (['string', 'boolean'].includes(type) || (type === 'number' && !isNaN(value))) {
            simpleObj[key] = value;
        } else if (type === 'object') {
            Object.assign(simpleObj, destructure(value));
        }
    }
    return simpleObj;
}

console.log(destructure(obj));
Enter fullscreen mode Exit fullscreen mode

for (let key in obj) {-> 对给定的对象进行迭代。

const value = obj[key];
const type = typeof value;
Enter fullscreen mode Exit fullscreen mode

捕捉实际value及其type

if (['string', 'boolean'].includes(type) || (type === 'number' && !isNaN(value))) {
            simpleObj[key] = obj[key];
Enter fullscreen mode Exit fullscreen mode

验证 key 的值是否不是。如果不是 ,object则复制到obj sampleObjobject

else if (typeof obj[key] === 'object') {
            Object.assign(simpleObj, destructure(obj[key]));
        }
Enter fullscreen mode Exit fullscreen mode

对于对象,再次调用相同的函数(称为recursion)以转到对象的嵌套层级。此外,将所有内容赋值给sampleObj。因此,最终这个单一对象将包含所有键值对。

最后,返回该对象并将其打印到console

如果我们能以更好的方式实现这一点,我将非常感激您的建议。谢谢。


💎 很高兴看到你的回复

  1. 点赞- 您到达此​​处的意思是:我认为,我值得点赞。
  2. 评论——我们可以一起学习。
  3. 分享——让其他人也发现此资源有用。
  4. 订阅/关注——及时了解我的每日文章。
  5. 鼓励我-你可以给我买杯咖啡

我们进一步讨论一下。

  1. 只需直接联系@urstrulyvishwak
  2. 或者提及
    @urstrulyvishwak

进一步更新:

关注@urstrulyvishwak

文章来源:https://dev.to/urstrulyvishwak/convert-nested-json-to-simple-json-in-javascript-4a34
PREV
每个 Node 开发人员必须掌握的 10 个 JavaScript 概念
NEXT
我最常用的 5 个网页设计工具