简体   繁体   中英

Split object keys with same prefix to new objects

For example, given an object with keys and values

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

I want convert into two objects:

  1. prefix_1 with keys and values {a: 1a, b: 1b}
  2. prefix_2 with keys and values {a: 2a, b: 2b}

another example,given a formData 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"]

and I want to convert to 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. how to search and add key and value under a position when match same prefix

here is my code:

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

It can be a costly transformation, but not that complex:

Let's start with the input:

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

Then have a look at the desired 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",
  }
]

And here's a transformation from data to 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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