0

I have a sample JSON like this-

{
    "mode":"bikes",
    "from":"New work",
    "to":"britain"
}

And I want this JSON to be like this

{
    "packages.$.itinerary.$[item].mode":"bikes",
    "packages.$.itinerary.$[item].from":"New work",
    "packages.$.itinerary.$[item].to":"britain"
}
Juhil Somaiya
  • 873
  • 7
  • 20
  • What do you actually have? A JSON string or a JS object? And what have you tried so far? – Teemu Jan 17 '20 at 06:13
  • 2
    If it's not a string, it ain't no [JSON](http://json.org) -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jan 17 '20 at 06:17
  • It a json object from postman – Ashin Mahat Jan 17 '20 at 06:19
  • I just want to change the key name – Ashin Mahat Jan 17 '20 at 06:20
  • 1
    Again, what do you actually have? A JSON string or a JavaScript object? _JSON object_ in JavaScript is [an intrinsic object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) containing some methods for JSON handling. – Teemu Jan 17 '20 at 06:29

2 Answers2

0

Using Object.entries with Array.prototype.forEach to achieve:

const json = {
    "mode":"bikes",
    "from":"New work",
    "to":"britain"
};

const newJson = {};

Object.entries(json).forEach(([key, value]) => newJson['packages.$.itinerary.$[item].' + key] = value);

console.log(newJson);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0
    //using extra memory
    const obj = {
        "mode":"bikes",
        "from":"New work",
        "to":"britain"
    }

    const result = {};

    for(let i in obj) {
        if(obj.hasOwnProperty(i)) {
            result[`packages.$.itinerary.$[item].${i}`] = obj[i];
        }
    }

    console.log(result);

    // In-Place
    const obj = {
        "mode":"bikes",
        "from":"New work",
        "to":"britain"
    }

    for(let i in obj) {
        if(obj.hasOwnProperty(i)) {
            obj[`packages.$.itinerary.$[item].${i}`] = obj[i];
            delete obj[i];
        }
    }

    console.log(obj);

Karan Singh
  • 400
  • 1
  • 2
  • 13