I am trying to find a way to build my custom array, but I am not able to do so.
What I have done so far:
I have my array constructed like so:
const super_array = [];
super_array.push({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
});
Further down into the code, I want to assign new data to the array, like so :
for(let j=0; j<results.length; j++) {
priceNumber = parseFloat(results[j].replace('<span>Lei</span>', '')) ;
super_array.push({price: priceNumber})
}
Result:
Right now, I get the following structure:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
}, {pret: priceNumber});
What I would like to get is:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit,
pret: priceNumber
});
I am not sure if I have explained it correctly. Basically I want to have the priceNumber uniquely match with the other data in the existing array, and not to be added as a separate index.
super_array[0].pret = priceNumber
super_array.push adds a new object to the array. What you are trying to do in the last code is adding a property to an object of the array.
For example: super_array[0].pret = priceNumber will add the property pret with the value of priceNumber. Here I'm not adding new objects to the array.
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I am new in coding JavaScript. So far I know how to set and get values from a multi array, but with this one I cannot find the right way to do it.
I am trying to get the email value from this array:
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
I tried
JSON.parse(__ar.tag.email)
document.write(__ar[2][2])
Everything I tried so far I got either undefined or tag[object, object].
What's the easiest way to get it?
The email property is located on the second element of the array (that is index 1 of the zero based indexed array). So, to access it, you also need to access the second object of the element (again index 1) and then .email is at your hand:
document.write(__arr[1][1].email);
Assuming that you only push those two values, your array looks like the following:
[
['id' ,'12541'],
['tag', {"sub":false,"email":"email#email.com"}]
]
Means, that when you access it using __arr.tag.email will result in an undefined error, because it's an array not an object.
Therefore what you could do is, if you don't know exactly the index:
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
for (var i = 0; i < __arr.length; i++){
if(__arr[i][0] === 'tag'){
console.log(__arr[i][1].email);
break;
}
}
so you have an array as __arr, the first element you are pushing is id which is an array second array is having your email id.
so you can access as shown below.
I hope this will solve your issue
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log("email id =>", __arr[1][1].email)
I hope you know array is starting from its index that's base value is 0. in your code there is no such element which is available in index 2.
document.write(__ar[2][2]) //
I know lots of answer is given here, but i just want to tell you even you are pushing value in "__arr" i.e an array of array. so every element is storing in its index value.
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log(__arr[0]) //return you ["id", "12541"]
console.log(__arr[1]) //return you ["tag", {sub: false, email: "email#email.com"}]
again you can see inside of your "__arr" there is a an array element
console.log(__arr[0][0]) //return you "id"
console.log(__arr[0][1]) //return you "12541"
console.log(__arr[1][0]) //return you "tag"
console.log(__arr[1][1]) //return you {sub: false, email: "email#email.com"}
and here what you want i.e.
console.log(__arr[1][1].sub) //return you false
console.log(__arr[1][1].email) //return you "email#email.com"
A dynamic way to do it (with level of 2 nested levels).
Basically, I used two nested loops and aggregated the emails into a list.
let __arr = []
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
__arr.push(['tag2', {"sub":false,"email":"2222#email.com"}]);
const emails = __arr.reduce((res, items) => {
items.forEach(elem => {
if (elem.email) res.push(elem.email)
})
return res
},[])
console.log(emails)
// [ 'email#email.com', '2222#email.com' ]
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.
I am trying to build a data structure.
In my limited knowledge, 'hash table' seems to be the way to go. If you think there is an easier way, please suggest it.
I have two, 1-dimensional arrays:-
A[] - contains names of badges (accomplishment)
B[] - contains respective dates those achievements were accomplished from array A[].
An achievement/accomplishment/badge can be accomplished more than one time.
Therefore a sample of the two arrays:-
A['scholar', 'contributor', 'teacher', 'student', 'tumbleweed', 'scholar'.....,'scholar',......]
B['1/2010', '2/2011', '3/2011', '6/2012', '10/2012', '2/2013',......'3/2013',........]
What I want to achieve with my data structure is:-
A list of unique keys (eq:- 'scholar') and all of its existing values (dates in array B[]).
Therefore my final result should be like:-
({'scholar': '1/2010', '2/2013', '3/2013'}), ({'contributor' : ........})..........
This way I can pick out a unique key and then traverse through all its unique values and then use them to plot on x-y grid. (y axis labels being unique badge names, and x axis being dates, sort of a timeline.)
Can anyone guide me how to build such a data structure??
and how do I access the keys from the data structure created.... granted that I don't know how many keys there are and what are their individual values. Assigning of these keys are dynamic, so the number and their names vary.
Your final object structure would look like this:
{
'scholar': [],
'contributor': []
}
To build this, iterate through the names array and build the final result as you go: if the final result contains the key, push the corresponding date on to its value otherwise set a new key to an array containing its corresponding date.
something like:
var resultVal = {};
for(var i = 0; i < names.length; ++i) {
if(resultVal[names[i]]) {
resultVal[names[i]].push(dates[i]);
} else {
resultVal[names[i]] = [dates[i]];
}
}
Accessing the result - iterating through all values:
for(var key in resultVal) {
var dates = resultVal[key];
for(var i = 0; i < dates.length; ++i) {
// you logic here for each date
console.log("resultVal[" + key + "] ==> " + resultVal[key][i]);
}
}
will give results like:
resultVal[scholar] ==> 1/2010
resultVal[scholar] ==> 2/2013
resultVal[scholar] ==> 3/2013
resultVal[contributor] ==> 2/2011
resultVal[teacher] ==> 3/2011
resultVal[student] ==> 6/2012
resultVal[tumbleweed] ==> 10/2012
You can try this...
var A = ['scholar', 'contributor',
'teacher', 'student', 'tumbleweed', 'scholar','scholar'];
var B = ['1/2010', '2/2011',
'3/2011', '6/2012', '10/2012', '2/2013','3/2013'];
var combined = {};
for(var i=0;i<A.length;i++) {
if(combined[A[i]] === undefined) {
combined[A[i]] = [];
}
combined[A[i]].push(B[i]);
}
Then each one of the arrays in combined can be accessed via
combined.scholar[0]
or
combined['scholar'][0]
Note the === when comparing against undefined
Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.