Search code examples
javascriptphpjsonlaravelkey-value

Separate Id and name in key of JSON


I have data on worker in my database in JSON format. which looks like this

{"45051-Cortador 1 Siloc": "hsgvs", "45063-Nihil impedit quia": "okbbd",}

in this JSON Key contains id and name of user for example in first key 45051 is id and Cortador 1 Siloc is name of user. I want id from key so that I can use it and I want to use it in Laravel Controller(PHP). Thanks,


Solution

  • You can use split here

    const obj = {
      "45051-Cortador 1 Siloc": "hsgvs",
      "45063-Nihil impedit quia": "okbbd",
    };
    
    const result = Object.keys(obj).map((s) => s.split("-"));
    
    console.log(result);
    
    result.forEach(([k, v]) => console.log(k, v));
    /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }