Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

javascript - 嵌套对象的键在格式化和呈现后丢失(Nested objects' key is missing after it is formatted and rendered)

I have this object which I have been trying to print in my ejs template without object syntaxes.

(我有一个我一直试图在没有对象语法的ejs模板中打印的对象。)

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.

(我在StackOverflow中遵循了一个答案,并且在没有语法的情况下成功打印了它,但是它并没有打印嵌套对象中的所有内容。)

What I mean is there are two nested objects in data(f and g).

(我的意思是在data(f和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': '[email protected]',
                    phone: '+12345678',
                    country: 'USA',
                    car: 'Toyota Prius' 
                },
                'g':{ 
                    name: 'Sophie',
                    'e-mail': '[email protected]',
                    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('
');
            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,[email protected],+12345678,USA,Toyota Prius
G: Sophie,[email protected],+12345678,UK,Nissan Bluebird
H: Volkswagen
I: Bugatti
J: % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s

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

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

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

Expected result:

(预期结果:)

A: Tesla
B: Mclaren
C: Ferrari
D: Lamborghini
E: Lotus
F: 
Name: John
Email: [email protected]
Phone: +12345678
Country: USA 
Car: Toyota Prius
G: 
Name: Sophie
Email: [email protected]
Phone: +12345678
Country: UK
Car: Nissan Bluebird
H: Volkswagen
I: Bugatti
J: 
% mileage
% top speed
% suspension
% navigation
% horsepower
% 0-60s
  ask by Zak translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...