0

I am generating a JavaScript object based on a CSV file that I have.

Here is what the object currently looks like-- an array of objects:

     [
        {
        "country": "afghanistan",
        "iso3": "afg",
        "first_characteristic": 3,
        "second_characteristic": 5,
        "third_characteristic": 3
        },
        {
        "country": "united states",
        "iso3": "usa",
        "first_characteristic": 8,
        "second_characteristic": 6,
        "third_characteristic": 7
        },
        {
        "country": "china",
        "iso3": "chn",
        "first_characteristic": 6,
        "second_characteristic": 0.7,
        "third_characteristic": 2
        }
    ]

The fiddle is here.

I'd like to add a name to each object, that is derived from one of its values, and for the output to be a nested object.

So this is what I want the new object to look like:

    {
        "afg":{
        "country": "afghanistan",
        "iso3": "afg",
        "first_indicator": 3,
        "second_indicator": 5,
        "third_indicator": 3
        },
        "usa":{
        "country": "united states",
        "iso3": "usa",
        "first_indicator": 8,
        "second_indicator": 6,
        "third_indicator": 7
        },
        "chn":{
        "country": "china",
        "iso3": "chn",
        "first_indicator": 6,
        "second_indicator": 0.7,
        "third_indicator": 2
        }
    }

I can't figure out how to add these names. Any help is greatly appreciated.

3
  • 1
    Please note [foo: bar, fizz: buzz] is not a valid Array in JavaScript. Are you saying you want both indices and keys? just keys? just indicies but labels somehow attached? Commented Nov 24, 2015 at 2:13
  • Your target json looks incorrect as each element of the array is of the form "...": {...}. Is there any need for it to be an array, could it be an object? Commented Nov 24, 2015 at 2:16
  • What have you tried so far to convert the object? Can you share an attempt you've made or started on? Or, detail a guess of how you think it might work? Commented Nov 24, 2015 at 2:21

2 Answers 2

2

In one line using ES6, where arr is your data as an Array and obj is the resulting Object

var obj = arr.reduce((o, e) => ((o[e.iso3] = e), o), {});
Sign up to request clarification or add additional context in comments.

Comments

0

try this,

function setNameToJSONObj(json){

  var rslt = [];

  for(var i = 0; i< json.length; i++){
    rslt[json[i].iso3] = json[i];
  }
  return rslt;
}

1 Comment

Thank you, this is also helpful!

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.