skip to Main Content

i have array of object where some key values are set in comma seperated
here below is sample object how it is

var data = [{
  "id":1,
  "x, y, z" :"1,2,3"
}, {
  "id":2,
  "x, y, z" :"10,12,153"
}, {
  "id":3,
  "x, y, z" :"9,8,5"
}, {
  "id":4,
  "x, y, z" :"14,87,13"
}]

here is the expected output

[{
  "id":1,
  "x":1,
  "y":2,
  "z":3
},{
  "id":2,
  "x":10,
  "y":12,
  "z":153
},{
  "id":3,
  "x":9,
  "y":8,
  "z":5
},{
  "id":4,
  "x":14,
  "y":87,
  "z":13
}]

here below is code i tried,

const outputArray = data.map((item:any, index:number) => {
      let commaHeaders = Object.keys(item)[index]?.split(',');
      console.log(commaHeaders)
      if(commaHeaders && commaHeaders.length >= 2) {
        commaHeaders.map((comma) =>{
          item[comma] = comma.trim();
        })
      }
      return item
});

Note
the function should be generic, in some case i will get a,b,c as a key values instead of x,y,z
any help or suggestions are really helpful!

3

Answers


  1. Something like:

    function decommafy(obj) {
      const newObj = {};
      for (const [key, value] of Object.entries(obj)) {
        if (key.includes(",") && typeof value === "string") {
          const keys = key.split(",");
          const values = value.split(",");
          for (let i = 0; i < keys.length; i++) {
            newObj[keys[i].trim()] = values[i].trim();
          }
        } else {
          newObj[key] = value;
        }
      }
      return newObj;
    }
    
    const result = [
      {
        id: 1,
        "x, y, z": "1,2,3",
      },
      {
        id: 2,
        "fnef, fnerdl": "farb,forb",
        "zub,zab": "zeeb,zib",
      },
    ].map(decommafy);
    
    console.log(result);

    This doesn’t automatically cast the values to Numbers, but you can trivially add that.

    Login or Signup to reply.
  2. You could split all key/value pairs (by comma with optional whitespace) and convert finite values to numbers.

    const
        data = [{ "id": 1, "x, y, z": "1,2,3" }, { "id": 2, "x, y, z": "10,12,153" }, { "id": 3, "x, y, z": "9,8,5" }, { "id": 4, "x, y, z": "14,87,13" }],
        result = data.map(o => Object.fromEntries(Object
            .entries(o)
            .flatMap(([k, v]) => {
                const
                    kk = k.split(/s*,s*/),
                    vv = v.toString().split(/s*,s*/).map(v => isFinite(v) ? +v : v);
                    
                return kk.map((k, i) => [k, vv[i]]);
            })    
        ));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
  3. Something like this should work

        const outputArray = data.map((item) => {
          // Extract the keys of item
          let keys = Object.keys(item);
          // Find the key with comma
          const commaKey = keys.find((key) => key.includes(','));
          // Extract the properties
          const commaHeaders = commaKey.split(', ');
          // Extract the values
          const commaValues = items[commaKey].split(', ');
          // Assign the right value to the right key in item
          commaHeaders.forEach((key, index) => {
            item[key] = commaValues[index];
          });
          // Delete the original property
          delete item[commaKey];
          return item
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search