I have the json string like,
string js=[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]
And I need to convert this into like the following format using java script.
[['Pini',111],['Yaniv',123],['Yoni',145]]
How to convert the json string into javascript array using javascript function?
I think something like this:
var ret = [];
for (var i = 0; i < js.length; i++) {
ret.push([js[i].Name, js[i].ID]);
}
// ret holds your array of arrays
Or something like:
var ret = $.map(js, function (el, i) {
return [[el.Name, el.ID]];
});
An example of both: http://jsfiddle.net/RNY8M/
You can do like this
JsFiddler Demo of below code
var JSONObject = {"results":[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]};
var Users= [];
$.each(JSONObject.results, function(i, obj)
{
alert(obj.Name);
alert(obj.ID);
Users.push([obj.Name, obj.ID]);
});
For this kind of transformations I always prefer using UnderscoreJs which is an utility-belt library (mainly for object/array transformations) for Javascript. I think that it provides great functions that make life easier, allowing javascript developers to be more productive and to achieve a better legibility for the resulting code.
Here is the solution with underscore (extended):
var js=[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]
var names = _.pluck(js, 'Name');
var ids = _.pluck(js, 'ID');
var result = _.zip(names, ids)
And you achive the desired result:
[['Pini',111],['Yaniv',123],['Yoni',145]]
Solution in one line with underscorejs:
var result = _.zip(_.pluck(js, 'Name'), _.pluck(js, 'ID'))
Hope it helps!
Here's a solution that will work for a simple object (not deep objects, though.... but I'll leave that for you to implement).
http://jsfiddle.net/eUtkC/
var js = [{
"Name": "Pini",
"ID": "111"},
{
"Name": "Yaniv",
"ID": "123"},
{
"Name": "Yoni",
"ID": "145"}]
function obj2arr(obj) {
var i, key, length = obj.length,
aOutput = [],
aObjValues;
for (i = length - 1; i >= 0; i--) {
aObjValues = [];
for (key in obj[i]) {
if (obj[i].hasOwnProperty(key)) {
aObjValues.push(obj[i][key]);
}
}
aOutput.push(aObjValues);
}
return aOutput;
}
document.write(JSON.stringify(obj2arr(js)))
EDIT
Here's a version using Array.prototype.map:
http://jsfiddle.net/eUtkC/1/
function obj2arr(obj) {
var key, aOutput = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
aOutput.push(obj[key]);
}
}
return aOutput;
}
document.write(JSON.stringify(js.map(obj2arr)))
I correct my solution, I hadn't read well the specs (my fault):
var jsonArray = [{"Name":"Pini","ID":"111"}, {"Name":"Yaniv","ID":"123"}, {"Name":"Yoni","ID":"145"}];
var jsonConverted = {};
$(jsonArray).each( function() {
jsonConverted.push([ this.Name, this.ID ]);
});
This solution uses jQuery.
Related
I have the following code but I know that there must be a more efficient way to get to my end results. I need a comma separated string but when I try to use .toString I know that I'm not using it in the right place. I've included the code that I am currently using
function load_data() {
var response = [
{"email": "a#123.com","pmid": ["a22222", "a444444", "a555555", "a7777777", "a8888888"]},
{"email": "b#123.com", "pmid": ["b22222", "b444444", "b555555", "b7777777", "b8888888"]},
{"email": "c#123.com", "pmid": ["c22222", "c444444", "c555555", "c7777777", "c8888888"]},
{"email": "d#123.com", "pmid": ["d22222", "d444444", "d555555", "d7777777", "d8888888"]}
];
var singleEmail = $.grep(response, function (element, index) {
return element.email == 'a#123.com';
});
var obj = singleEmail[0];
var pmid = obj.pmid;
var pmidList = ''
for (var i = 0; i < pmid.length; i++) {
pmidList += pmid[i] + ',';
}
alert(pmidList);
}
Also is using grep any more efficient than just looping?
Thanks
Using jQuery is never more efficient. JS has many useful methods these days. Check MDN for browser support though.
Find the right element:
// modern
const element = response.find((el) => el.email == 'a#123.com');
// compatible
var element = response.find(function(el) {
return el.email == 'a#123.com';
});
Stringify the array:
const pmidList = element.pmid.join(',');
// or var for compatibility
pmidList won't have a trailing , like your code, but I'm guessing that's good.
References & support:
const vs var
arrow functions
array.find vs array.filter (grep)
I have below json parse data and i am trying to convert it to javascript object
usrPrefs
[Object { name="mystocks", value="500400,532500,500180,500312,500325"},
Object { name="mystocksname", value="Tata Power,Maruti Suzuki...NGC,Reliance Industries"},
Object { name="refresh_secs", value="600"}]
i am trying to convert this to something like below
myparam = {
mystocks:500400,532500,500180,500312,500325,
mystocksname:Tata Power,Maruti Suzuki...NGC,Reliance Industries
....
}
how i can do that in javascript something like using loop or any build in function, i started learning javascript and i am stuck here...
thank you in advance.
Regards,
Mona
You could use the reduce function in order to achieve that:
var myparam = usrPrefs.reduce(function(a, b){
a[b.name] = b.value;
return a;
}, {});
You might choose to use array instead of string, its more convenient for you to use
function toMap(usrPrefs){
var result = {};
for(var i = 0 ; i < usrPrefs.length ; i++){
var obj = usrPrefs[i];
var array = obj.value.split(',').trim();
result[obj.name] = array;
}
return result;
};
Try this code:
var myparam = {};
for (var i = 0; i < usrPrefs.length; i++) {
myparam[usrPrefs[i].name] = usrPrefs[i].value;
}
I have a JSON array of name/value pairs and I'm looking at a sensible way to be able to adjust the value for a particular name in the array. e.g.
var myArr = [{"name":"start","value":1},{"name":"end","value":15},{"name":"counter","value":"6"},{"name":"user","value":"Bert"}]
I can use
$.each(myArr, function (key, pair) {
if (pair.name == 'user')
{
pair.value = 'bob';
}
});
but in reality my object has tens of values and I would like to be able to change them much more simply than adding an if for each one.
Ideally myArr['user'].value = 'bob'; or something similar.
You have an array of objects in an array. An array does not have any indexing method that gives you direct lookup like you asked for;
myArr['user'].value = 'bob';
To get that, you would need to restructure your data so that you had an object where the name was the main key and inside that key was another object with the rest of your data for that user like this:
var myData = {
"start": {value: 1},
"end": {value: 15},
"user": {value: Bert}
};
The, you could directly access by name as in:
myData['user'].value = 'bob;
If you wanted to stick with your existing data structure, then the simplest thing I can think of is to make a simple function that finds the right object:
function findUser(data, nameToFind) {
var item;
for (var i = 0; i < myArr.length; i++) {
item = nameToFind[i];
if (item.name === nameToFind) {
return item;
}
}
}
var myArr = [{"name":"start","value":1},{"name":"end","value":15},{"name":"counter","value":"6"},{"name":"user","value":"Bert"}]
Then, you could do something like this:
findUser(myArr, "user").value = "bob";
This assumes you're only looking for data that is in the array because otherwise, this will create an error unless you add error checking to it.
If you just really want to turn the whole thing into a function that finds and changes the name, it can be like this:
function changeUser(data, nameToFind, newName) {
var item;
for (var i = 0; i < myArr.length; i++) {
item = nameToFind[i];
if (item.name === nameToFind) {
item.name = newName;
return;
}
}
}
I will award the points for the best answer, but I actually solved it a completely different way:
First build up a list of "names" in the order they appear:
var keys = [];
$.each(myArr, function (key, pair) {
keys.push(pair.name);
});
then I can use:
myArr[keys.indexOf('sEcho')].value = 'whatever';
Try This
$.grep(myArr,function(e){return e.name=="user"})[0].value="ppp"
You can use the $.greb() of jquery.
Add this function:
function SetArrayValue(arr, key, value, stopOnFirstMatch) {
for (var i=0; i<arr.length; i++) {
if (arr[i].name === key) {
arr[i].value = value
if (stopOnFirstMatch !== undefined && stopOnFirstMatch) return
}
}
}
Then use it this way:
SetArrayValue(myArr, 'user', 'bob')
I am making a jquery ajax call to the following text file:
sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End
The call is working fine. But I really don't know how to access a particular value like lets say, 'China' from the above text file? I am trying tis for the first time. please help..
Here is the parseParams plugin which you can use to split a querystring into an array.
You can use it like this:
var querystring = 'sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End';
var paramsObj = $.parseParams(querystring);
alert(paramsObj.sport); // = Table Tennis
Don't use such file structure. Use JSON instead. i.e:
{
"sport":"Table Tennis",
"groups":false,
"no_groups":"",
"grp_names":[
],
"teams":[
{
"China":6157
},
{
"Finland":6158
},
{
"Sweden":6159
},
{
"Japan":6149
},
{
"Korea":6154
}
],
"Endstr":"End"
}
Then, after you parse it with $.get or $.ajax, you just access:
data.sports
for example.
Here is code to parse your data. It would have been straight forward if you have chosen JSON as return data.
function myParser() {
var str = "sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End";
var arPairs = str.split("&");
var outObj = {};
for (var i=0; i < arPairs.length; i++) {
var arTemp = arPairs[i].split("=");
var key = arTemp[0];
var value = arTemp[1];
if (key === "teams") {
arTemp = value.split("~");
var teamObj = {};
for (var j=0; j < arTemp.length; j++) {
var arTeamData = arTemp[j].split("^");
teamObj[arTeamData[1]] = arTeamData[2];
}
value = teamObj;
}
outObj[key] = value;
}
return outObj;
}
output: Is an array having all your data available. You can refer it as:
var outObj = myParser();
console.log(outObj.sport); // Prints "Table Tennis"
console.log(outObj.teams.china) // Prints china data
I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']