javascript - 嵌套对象的键在格式化和渲染后丢失

标签 javascript node.js object ejs

我有一个对象,我一直在尝试在没有对象语法的情况下在我的 ejs 模板中打印它。我在 StackOverflow 中遵循了一个答案,并成功地在没有语法的情况下打印了它,但它并没有打印嵌套对象中的所有内容。我的意思是数据中有两个嵌套对象(f 和 g)。因此,输出中缺少那些嵌套对象(如姓名、电子邮件、电话、国家/地区、汽车)中的属性(键)。我怎样才能用他们所尊重的值(value)观来呈现它?

这是对象和我用来格式化它的代码:

router.get("/", async(req, res) => {
    try{
        let data = { 
                a: 'Tesla',
                b: 'Mclaren',
                c: 'Ferrari',
                d: 'Lamborghini',
                e: 'Lotus',
                'f':{ 
                    name: 'John',
                    'e-mail': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="255d5c5f65405d44485549400b464a48" rel="noreferrer noopener nofollow">[email protected]</a>',
                    phone: '+12345678',
                    country: 'USA',
                    car: 'Toyota Prius' 
                },
                'g':{ 
                    name: 'Sophie',
                    'e-mail': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4cccdcef4d1ccd5d9c4d8d19ad7dbd9" rel="noreferrer noopener nofollow">[email protected]</a>',
                    phone: '+12345678',
                    country: 'UK',
                    car: 'Nissan Bluebird' 
                },
                h: 'Volkswagen',
                i: 'Bugatti',
                j:[ 
                    '% mileage',
                    '% top speed',
                    '% suspension',
                    '% navigation',
                    '% horsepower',
                    '% 0-60s' 
                ] 
            }
            var result = Object.entries(data).reduce((result, [key, value]) => {
                key = key.replace(/([A-Z]|\d+)/g, ' $1').replace(/^(.)/, (unused, p1) => p1.toUpperCase());
                if (!['string', 'number', 'boolean'].includes(typeof value)) {
                    value = Object.entries(value).map(([key, value]) => (typeof value == 'boolean') ? (value ? key : undefined) : value).filter(v => v !== undefined).join(',');
                }
                result.push(`${key}: ${value}`);
                return result;
            }, []);
            var finalData = result.join('\n');
            res.render("data", {data: finalData});
    }catch(e){
        req.flash("error", "Unable to retrieve data. Please try again!");
        res.redirect("/");
    }
});

这是我在控制台中打印的结果:

A: Tesla
B: Mclaren
C: Ferrari
D: Lamborghini
E: Lotus
F: John,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="770f0e0d37120f161a071b125914181a" rel="noreferrer noopener nofollow">[email protected]</a>,+12345678,USA,Toyota Prius
G: Sophie,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="18606162587d60797568747d367b7775" rel="noreferrer noopener nofollow">[email protected]</a>,+12345678,UK,Nissan Bluebird
H: Volkswagen
I: Bugatti
J: % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s

这是我在 ejs 模板中渲染后的结果:

A: Tesla B: Mclaren C: Ferrari D: Lamborghini E: Lotus F: John,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="423a3b3802273a232f322e276c212d2f" rel="noreferrer noopener nofollow">[email protected]</a>,+12345678,USA,Toyota Prius G: Sophie,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cf4f5f6cce9f4ede1fce0e9a2efe3e1" rel="noreferrer noopener nofollow">[email protected]</a>,+12345678,UK,Nissan Bluebird H: Volkswagen I: Bugatti J: % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s

预期结果:

A: Tesla
B: Mclaren
C: Ferrari
D: Lamborghini
E: Lotus
F: 
Name: John
Email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a6263605a7f627b776a767f34797577" rel="noreferrer noopener nofollow">[email protected]</a>
Phone: +12345678
Country: USA 
Car: Toyota Prius
G: 
Name: Sophie
Email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8ab91b4a9b0bca1bdb4ffb2bebc" rel="noreferrer noopener nofollow">[email protected]</a>
Phone: +12345678
Country: UK
Car: Nissan Bluebird
H: Volkswagen
I: Bugatti
J: 
% mileage
% top speed
% suspension
% navigation
% horsepower
% 0-60s

最佳答案

这不太漂亮,但应该可以做到:

var result = Object.entries(data).reduce((result, [key, value]) => {
   key = key.toUpperCase();
   if (typeof value === 'object') {
     result.push(`${key}:`);
     if (Array.isArray(value)) {
       value.forEach(item => result.push(item));
     } else {
       Object.entries(value).forEach(([key, value]) => {
         key = key.charAt(0).toUpperCase() + key.slice(1)
         result.push(`${key}: ${value}`);
       })
    } 
  } else {
    result.push(`${key}: ${value}`);
  }
  return result;
}, []);
var finalResult = result.join("\n");

关于javascript - 嵌套对象的键在格式化和渲染后丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120590/

相关文章:

javascript - 尝试使用 Greasemonkey 创建一个可以运行 Javascript 的按钮。

javascript - Socket.io Express 3 节课

json - 在 NodeJS 中将 Protobuf 响应转换为 JSON

javascript - 是否可以使用 C# 添加 Object 的属性

javascript - 如何知道哪个域使用 JS 向我的 C# 操作发送请求

javascript - Material-UI:提供给 createMuiTheme 的阴影数组应该支持 25 个高度

javascript - JS - 单击按钮将元素的文本更改为未定义

node.js - 使用axios发送请求时如何设置代理?

用于从位于服务器中的 .ser 文件读取对象的 Java 程序

java - 如何从 XML 文件创建对象图?