You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:48:14