2

I have this json string.

user_json_str = 
"
[{
    "id": 1,
    "lg_name": "foo",
    "lg_password": "bar"
},
{
    "id": 2,
    "lg_name": "user",
    "lg_password": "passwd"
}
]
";

I would like to manipulate it such that it becomes a javascript object that looks like this;

user_obj =
{
     foo: {
         id: 1,
         password: 'bar'
     },
     user: {
         id: 2,
         password: 'passwd'
     }
};

I am using node.js v4.6. I am at a loss how to begin. Some hints as starting points would be helpful.

0

4 Answers 4

4

You could parse the string and build an object with names as key.

var user_json_str = '[{"id":1,"lg_name":"foo","lg_password": "bar"},{"id":2,"lg_name": "user","lg_password":"passwd"}]',
    array = JSON.parse(user_json_str),
    object = {};

array.forEach(function (a) {
    object[a.lg_name] = { id: a.id, password: a.lg_password };
});

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

2

You can use JSON.parse, to get array of object from string.

Then, you can use array.reduce to loop over object and parse into necessary format.

Sample

var user_json_str = '[{"id":1,"lg_name":"foo","lg_password": "bar"},{"id":2,"lg_name": "user","lg_password":"passwd"}]';

var object = JSON.parse(user_json_str).reduce(function (p,o) {
    p[o.lg_name] = { id: o.id, password: o.lg_password };
  return p;
}, {});

console.log(object);

Comments

1

First, parse your array, create a new object, then loop through the array and build the object.

var arr = JSON.parse('[{"id": 1,"lg_name": "foo","lg_password": "bar"},{"id": 2,"lg_name": "user","lg_password": "passwd"}]');
var newObj = {}
for (var i = 0; i < arr.length; i++)
{
    newObj[arr[i].lg_name] = {id: arr[i].id, password: arr[i].lg_password}
}

Comments

0

Try using JSON.parse(user_json_str);

Comments

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.