首页 > 解决方案 > 将具有相同前缀的对象键拆分为新对象

问题描述

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

{
  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}

另一个例子,给定一个 formData 对象:

["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 对象

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. 匹配相同前缀时如何在位置下搜索和添加键和值

这是我的代码:

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;
          };
      }

标签: javascriptarraysobjectkey

解决方案


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

让我们从输入开始:

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",
}

然后看看所需的输出:

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",
  }
]

这是从datato的转换fruitprices

// 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)


推荐阅读