Search code examples
javascriptarraystypescriptvalidationdata-manipulation

split comma in the object key value and read the value


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!


Solution

  • 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.