user4790312
user4790312

Reputation:

JavaScript parse JSON and create Key Value array from that

i have simple json format like with this format:

{
    "Template": [
        {
            "ID": "856",
            "name": "users",
            "Template_Id": 0
        },
        {
            "ID": "857",
            "name": "avatars",
            "Template_Id": 1
        },
        {
            "ID": "858",
            "name": "emails",
            "Template_Id": 2
        }
    ]
}

now i'm trying to parse it and create key value array such as:

var sArray = {856:users, 857:avatars, 858:emails};

my code is not correct for create this array after parse json and i get this error:

Message: TypeError: obj.Template.name is undefined

My code is this:

    var obj = JSON.parse(jsonText);
    var count_templates = obj.Template.length;
    var template_array;

    /* Length is not static */
    for( i=0; i < count_templates; i++){
        id = obj.Template.ID;
        template_array[id] =  obj.Template.name;
    }
    for(var key in template_array)
    {
        console.log("key " + key + " has value " + template_array[key]);
    }

Upvotes: 2

Views: 1278

Answers (10)

Frederik.L
Frederik.L

Reputation: 5620

Yet another solution. The generic case is:

var arr = Object.keys(obj).map(function(k) {
    var o = {};
    o[obj[k].ID] = obj[k].name;
    return o;
});

You can modify this pattern to suit your need. Here, k is the current key being visited and obj is your data.

Update: now returns json object

Upvotes: 0

user663031
user663031

Reputation:

Using ES6:

Object.assign({}, ...data.Template.map(elt => ({[elt.ID]: elt.name})));

This maps the elements of data.Template into little objects each with one key-value pair, where the key is the element ID (using ES6 computed property names), and the value is the name. Then it feeds all these objects as parameters (using the ... spread operator) to Object.assign, which merges them together.

{ '856': 'users', '857': 'avatars', '858': 'emails' }

Using Underscore

On a completely different note, if you are amenable to using Underscore, then

_.object(_.pluck(obj.Template, 'ID'), _.pluck(obj.Template, 'name'))

Upvotes: 1

Mark C.
Mark C.

Reputation: 6450

Something like this:

var data = {
    "Template": [
        {
            "ID": "856",
            "name": "users",
            "Template_Id": 0
        },
        {
            "ID": "857",
            "name": "avatars",
            "Template_Id": 1
        },
        {
            "ID": "858",
            "name": "emails",
            "Template_Id": 2
        }
    ]
};

var output = [];

data.Template.forEach(function(item){
    output.push(item.ID + ":" + item.name); 
});

Although you may want to check if the object has the properties you're looking for first, but you get the idea.

Edit : Just noticed you wanted an output of type array. (even though you have {} surrounding your array. In this scenario, I would use map.

data.Template.map(function(item){
    output.push(item.ID + ":" + item.name); 
});

Thanks to @torazaburo for keeping me honest and making me re-read the question.

Upvotes: -1

A.T.
A.T.

Reputation: 26312

using map function

var arr = {};
data.Template.map(function(item,i){ 
   if(!!item.name && !!item.ID) //check if properties are valid
             arr[item.ID] = item.name;
});

return Object {856: "users", 857: "avatars", 858: "emails"}

http://jsfiddle.net/arunthakur14/hjgvkvLu/

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 1362

you can do by using reduce function

var arr = {
   "Template": [
    {
        "ID": "856",
        "name": "users",
        "Template_Id": 0
    },
    {
        "ID": "857",
        "name": "avatars",
        "Template_Id": 1
    },
    {
        "ID": "858",
        "name": "emails",
        "Template_Id": 2
    }
]
};
 var data = arr["Template"].reduce(function (output , val){ 
   output[val.ID] = val.name;
   return output;
}, {});

 console.log(data)

Upvotes: 0

user1090751
user1090751

Reputation: 336

First change the variable type of template_array i.e

var template_array=[];

and then iterate by using obj.Template[i] not obj.Template. Here is working code:

var obj = JSON.parse(jsonText);
var count_templates = obj.Template.length;
var template_array=[];

/* Length is not static */
for( i=0; i < count_templates; i++){
    id = obj.Template[i].ID;
    template_array[id] =  obj.Template[i].name;
}
for(var key in template_array)
{
    console.log("key " + key + " has value " + template_array[key]);
}

Upvotes: 0

Braj
Braj

Reputation: 46841

It's very simple. First of all as per sample output mentioned in your post sArray is not an array. It's an object.

Steps:

  1. Fisrt convert the actual JSON text into JSON object
  2. Get Template array from parsed JSON object
  3. Iterate Template array and create a new JSON object as expected

Sample code:

  var jsonText = '{"Template" : [{"ID":"1","name":"a"},{"ID":"2","name":"b"}]}';
var obj = JSON.parse(jsonText);
var arr = obj["Template"];

var sArray = {};
for(var i = 0; i < arr.length; i++) {
    var a = arr[i];
    sArray[a["ID"]] = a["name"];
}
document.write(JSON.stringify(sArray));

Upvotes: 0

Phil
Phil

Reputation: 164798

I'd use a simple reduce operation on the Template array.

var obj = {
    "Template": [
        {
            "ID": "856",
            "name": "users",
            "Template_Id": 0
        },
        {
            "ID": "857",
            "name": "avatars",
            "Template_Id": 1
        },
        {
            "ID": "858",
            "name": "emails",
            "Template_Id": 2
        }
    ]
};

var sArray = obj.Template.reduce(function(o, tpl) {
        o[tpl.ID] = tpl.name;
        return o;
    }, {});

document.getElementById('out').innerHTML = JSON.stringify(sArray);
<pre id="out"></pre>

Upvotes: 1

intekhab
intekhab

Reputation: 1596

Try this

var data = {
    "Template": [
        {
            "ID": "856",
            "name": "users",
            "Template_Id": 0
        },
        {
            "ID": "857",
            "name": "avatars",
            "Template_Id": 1
        },
        {
            "ID": "858",
            "name": "emails",
            "Template_Id": 2
        }
    ]
};


var temp = data.Template;
var res = {};
for (var i = 0; i < temp.length; i++) {
    res[temp[i]['ID']]  =  temp[i]['name'];
}

console.log(res);

Upvotes: 0

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5166

Change this to

   for( i=0; i < count_templates; i++){
      id = obj.Template.ID;//Here you are not actually accessing the array index element
      template_array[id] =  obj.Template.name;//Here you are not actually accessing the array index element
   }

   for( i=0; i < count_templates; i++){
      id = obj.Template[i].ID;
      template_array[id] =  obj.Template[i].name;
   }

Upvotes: 0

Related Questions