This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}
Related
I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe
I am writing a function that takes a string, splits it, and the uses json[key][key2][key3] formatting. The problem is n is potentially infinite (not literally but needs to written that way)
function getJsonValue(json,string) {
var vals = string.split(".");
var x = vals.length;
var string = '';
while (x != 0) {
string += "['"+vals[(vals.length-x)]+"']"
x--
}
return string;
}
That will produce, for example: "['condition']['item']['condition']['temp']"
I need to extract a value from that by attaching it to a json object, like
json"['condition']['item']['condition']['temp']"
But I don't know how or if that is even possible.
Edit:
The problem is I need any value from a config file to be passed in and then parsed from a returning function. I.e. User knows the value will be condition.item.condition.temp for this specific query. I am trying to write one function that covers everything and pass in config values for what I know to be the output. So, on one query, I might want the condition.item.condition.temp value and on another I might want condition.wind.chill .
I'm not sure if I understand 100% what you're trying to do, but if you're receiving a JS object json and a string in the format field1.field2.field3 and trying to get the value of json.field1.field2.field3 then you can do something like this:
function getJsonValue(json,string) {
var vals = string.split(".");
for (var i = 0; i < vals.length; i++) json = json[vals[i]];
return json;
}
It would work like this for a given object:
var obj = { field1: { field2: { field3: "Hello!" } } };
var res = getJsonValue(obj, "field1.field2.field3");
console.log(res); // prints Hello
See lodash get
_.get(json, 'key1.key2.key3')
you can build the "path" from your current code and ask lodahs to get the value out for you.
What about doing an eval?
var json = {
'one': {
'two': {
'three': {
'four': 4
}
}
}
};
alert(eval("json['one']['two']['three']['four']"))
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')
Here is my response code in jQuery:
var response = $.parseJSON(response);
for (var i = 0; i < response.groupIds.length; i++) {
console.log(response.groupIds[i], i);
}
Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.
I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?
Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.
var group = response.groupIds[i];
var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
var name = allPropertyNames[j];
var value = group[name];
// Do something
}
Your question's response format contains only one key-value pair. The code can then be reduced to:
var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list; = key name
var value = group[name];
If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.
for (var name in group) {
if (group.hasOwnProperty(name)) {
var value = group[name];
// Do something
}
}
Use a for..in loop:
for( x in response.groupIds[i]) {
// x is now your unknown key
// response.groupIds[i][x] is the unknown value
}
Since there is only one property of the object, that'll work nicely.