1

I have a JSON file with a lot of objects like this (e.g. properties of Pikemen unit >Heroes 3 btw<):

[ {
        "ID": 0,
        "AI": 80,
        "": null,
        "Level": 0,
        "Growth": 14,
        "Low": 20,
        "High": 50,
        "Town": 0,
        "Name": "Pikeman",
    }, etc.. ]

How could I make "Name" property the name of every object in my JSON file? Either in JS code or through formatting file. What I mean is:

[ "Pikeman": {
       "ID": 0,
       "AI": 80,
       etc..
} ]

2 Answers 2

1

Use it like this:

let obj = [{
        "ID": 0,
        "AI": 80,
        "": null,
        "Level": 0,
        "Growth": 14,
        "Low": 20,
        "High": 50,
        "Town": 0,
        "Name": "Pikeman",
    },{
        "ID": 0,
        "AI": 82220,
        "": null,
        "Level": 230,
        "Growth": 14,
        "Low": 20213,
        "High": 12312050,
        "Town": 10,
        "Name": "Pikeman2",
    }]

obj.forEach((item, index) => {
  obj[item.Name] = item;
  delete obj[index];
})

console.log(obj)
Sign up to request clarification or add additional context in comments.

1 Comment

I have a lot of objects like this. I need some kind of loop to do this, because file is too long
0

Hi @Adrian You can iterate through your array and obtain the name and assign int as a key check this:

let obj = [ {
        "ID": 0,
        "AI": 80,
        "": null,
        "Level": 0,
        "Growth": 14,
        "Low": 20,
        "High": 50,
        "Town": 0,
        "Name": "Pikeman",
    }, 
    {
        "ID": 0,
        "AI": 80,
        "": null,
        "Level": 0,
        "Growth": 14,
        "Low": 20,
        "High": 50,
        "Town": 0,
        "Name": "Pikeman1",
    }, 
    {
        "ID": 0,
        "AI": 80,
        "": null,
        "Level": 0,
        "Growth": 14,
        "Low": 20,
        "High": 50,
        "Town": 0,
        "Name": "Pikema2",
    }]

    let objConverted = {};

    obj.forEach( o => {
      objConverted[o.Name] = o; 
    } ) 

    console.log(objConverted);

Check this if you wanna play with the code : https://repl.it/repls/HalfSatisfiedMainframe

1 Comment

Works! Thanks a lot for useful tool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.