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.
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; }
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.
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);
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}
}
尝试使用JSON.parse(user_json_str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.