如何在JavaScript中构建按type分组的嵌套键值对结构?
Convert Flat Pant Entries to Structured Object
Got it, let's take your list of pant service entries and restructure them into that handy object you can easily query.
First, here's your original raw data for reference:
1. {type:"pant", service:"normal", price:"30"} 2. {type:"pant", service:"premium 1", price:"50"} 3. {type:"pant", service:"premium 2", price:"70"} 4. {type:"pant", service:"premium 3", price:"100"}
The Structured Result
We'll strip out the type field from each entry (since we're grouping all pants under the "pant" key) and wrap the remaining service/price pairs into an array assigned to the pant property of your x variable:
var x = { "pant": [ {service:"normal", price:"30"}, {service:"premium 1", price:"50"}, {service:"premium 2", price:"70"}, {service:"premium 3", price:"100"} ] };
How to Use It
Now you can access all the pant service entries exactly how you wanted:
- Use
x['pant']to get the full array of service/price objects - Or use dot notation:
x.pant(works since "pant" is a valid identifier without spaces)
For example, if you wanted to loop through all entries to log details:
x['pant'].forEach(entry => { console.log(`Service: ${entry.service}, Price: $${entry.price}`); });
内容的提问来源于stack exchange,提问作者Mukesh Singal
相关产品推荐
相关产品推荐

