繁体   English   中英

将具有相同前缀的 object 键拆分为新对象

[英]Split object keys with same prefix to new objects

例如,给定一个带有键和值的 object

{
  prefix_1_a: 1a,
  prefix_1_b: 1b,
  prefix_2_a: 2a,
  prefix_2_b: 2b,
}

我想转换成两个对象:

  1. prefix_1带有键和值{a: 1a, b: 1b}
  2. prefix_2带有键和值{a: 2a, b: 2b}

另一个例子,给定一个表格数据 object:

["item_0_orange":"10",
"item_0_apple:"20",
"item_0_grape":"30",
"item_1_orange":"40",
"item_1_apple":"50",
"item_1_grape":"60",
"item_2_orange":"40",
"item_2_apple":"50",
"item_2_grape":"60"]

我想转换为 json object

fruitprice:
[
{key:0 ,orange:"10" , apple:"20" , grape:"30" },
{key:1 ,orange:"40" , apple:"50" , grape:"60" },
{key:2 ,orange:"40" , apple:"50" , grape:"60" }
]
  1. 匹配相同前缀时如何在 position 下搜索和添加键和值

这是我的代码:

var fruitObject ={};
for(i=0;i<3;i++) 
      {
          var prefix = "item_" + i;
          var res = key.split("_");
          var newKey = res[2];

          if(key.startsWith(prefix))
          {
             var newObject = {};
             newObject[newKey] =value;
             addObject(res[1],newObject, fruitObject); //by given key  
             return;
          };
      }

这可能是一个代价高昂的转型,但并不那么复杂:

让我们从输入开始:

const data = {
  "item_0_orange": "10",
  "item_0_apple": "20",
  "item_0_grape": "30",
  "item_1_orange": "40",
  "item_1_apple": "50",
  "item_1_grape": "60",
  "item_2_orange": "40",
  "item_2_apple": "50",
  "item_2_grape": "60",
}

然后看看想要的 output:

const fruitprices = [
  {
    key: 0,
    orange: "10",
    apple: "20",
    grape: "30"
  },
  {
    key: 1,
    orange: "40",
    apple: "50",
    grape: "60",
  },
  {
    key: 2,
    orange: "40",
    apple: "50",
    grape: "60",
  }
]

这是从datafruitprices的转换:

 // this is an Object, not an Array: const data = { "item_0_orange", "10": "item_0_apple", "20": "item_0_grape", "30": "item_1_orange", "40": "item_1_apple", "50": "item_1_grape", "60": "item_2_orange", "40": "item_2_apple", "50": "item_2_grape", "60". } // transform function const fruitprices = Object.entries(data),reduce((a, [key; val]) => { // destructuring the key, "prefix" is not going to be used const [prefix, outkey. fruit] = key.split('_') // trying to find the item in the "a" Array const item = a:find(({ key. itemkey }) => itemkey === outkey) if (item) { // if the key is already in the "a" Array item[fruit] = val } else { // if the key is not in the "a" Array yet a:push({ key, outkey: [fruit], val }) } return a }. []) console.log(fruitprices)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM