嵌套对象的键在格式化和呈现后丢失 [英] Nested objects' key is missing after it is formatted and rendered

查看:70
本文介绍了嵌套对象的键在格式化和呈现后丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我一直试图在没有对象语法的ejs模板中打印的对象。我在StackOverflow中遵循了一个答案,并成功地在不使用语法的情况下进行了打印,但是并不能打印嵌套对象中的所有内容。我的意思是在data(f和g)中有两个嵌套对象。因此,输出中缺少这些嵌套对象(例如名称,电子邮件,电话,国家/地区,汽车)中的属性(键)。

I have this object which I have been trying to print in my ejs template without object syntaxes. I followed an answer here in StackOverflow and was successful in printing it without the syntaxes but it doesn't print everything in the nested object. What I mean is there are two nested objects in data(f and g). So the properties(keys) in those nested objects like name, email, phone, country, car are missing from the output. How can I also render that with their respected values?

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

Here's the object and the code which I used to format it:

router.get("/", async(req, res) => {
    try{
        let data = { 
                a: 'Tesla',
                b: 'Mclaren',
                c: 'Ferrari',
                d: 'Lamborghini',
                e: 'Lotus',
                'f':{ 
                    name: 'John',
                    'e-mail': 'xyz@example.com',
                    phone: '+12345678',
                    country: 'USA',
                    car: 'Toyota Prius' 
                },
                'g':{ 
                    name: 'Sophie',
                    'e-mail': 'xyz@example.com',
                    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("/");
    }
});

如果我在控制台中打印,则结果如下:

This is the result if I print it in the console:

A: Tesla
B: Mclaren
C: Ferrari
D: Lamborghini
E: Lotus
F: John,xyz@example.com,+12345678,USA,Toyota Prius
G: Sophie,xyz@example.com,+12345678,UK,Nissan Bluebird
H: Volkswagen
I: Bugatti
J: % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s

这是在我的ejs模板中呈现后的结果:

This is the result after I render it in my ejs template:

A: Tesla B: Mclaren C: Ferrari D: Lamborghini E: Lotus F: John,xyz@example.com,+12345678,USA,Toyota Prius G: Sophie,xyz@example.com,+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: xyz@example.com
Phone: +12345678
Country: USA 
Car: Toyota Prius
G: 
Name: Sophie
Email: xyz@example.com
Phone: +12345678
Country: UK
Car: Nissan Bluebird
H: Volkswagen
I: Bugatti
J: 
% mileage
% top speed
% suspension
% navigation
% horsepower
% 0-60s


推荐答案

这不是很漂亮,但是应该可以做:

This isn't pretty but should do the thing:

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");

这篇关于嵌套对象的键在格式化和呈现后丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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