What is the correct way to concatenate a string? - javascript

var d=getEntity( {"Division":
{
"oddTerms":
[
{
"entity": "Sunshine",
"Sunshine": [
{
"count": 2,
"entity": "Dodge"
},
{
"count": 1,
"entity": "Dodge Avenger"
},
]
}
]
}});
I want to traverse through the json string and the the entity names Dodge and Dodge Avenger. Ive used the following method
for (var k in h.Division.oddTerms)
{
s=h.Division.oddTerms[k].entity;
h.Division.oddTerms[k].+s+.entity;
}
But I do think this its not the correct methd to concatenate as it is not wrking.. anyone knows the correct format?

oddTerms is an Array, not an Object. For arrays in JavaScript you need to use a for loop with a counter instead of iterating through the elements:
var concatedString = '';
for (var k=0; k<h.Division.oddTerms.length;k++)
{
// Get the name of the entity we want to collect the entity terms of
var entityName =h.Division.oddTerms[k].entity;
// iterate through all the instances of each entity
for(var j=0; j<h.Division.oddTerms[k][entityName].length;j++){
concatedString += h.Division.oddTerms[k][entityName][j].entity;
}
}

var entityName = "",
arrTerms = [],
outputTemplate = '{"%entityName":[%terms]}',
h = {
"Division":
{
"oddTerms":
[
{
"entity": "Sunshine",
"Sunshine": [
{
"count": 2,
"entity": "Dodge"
},
{
"count": 1,
"entity": "Dodge Avenger"
},
]
}
]
}
};
for (var i = 0; i < h.Division.oddTerms.length; i++)
{
entityName=h.Division.oddTerms[i].entity; // "Sunshine"
terms = h.Division.oddTerms[i][entityName];
for (var j = 0; j < terms.length; j++) {
arrTerms.push('"' + terms[j].entity + '"');
}
}
// This will give you '{"Sunshine":["Dodge","Dodge Avenger"]}':
console.log(outputTemplate.replace('%entityName', entityName).replace('%terms', arrTerms.join(",")));
Edit:
Just some more on this.
JSON can be a bit confusing to work with if you're not used to working with JS and object and array "literals". In JS you can define objects and arrays in a number of ways, but the easiest (and the most preferred, by many developers) is with these literals.
Here's an example of an object:
var myObj = {
"some prop":"some value",
"anotherProp":"another value"
}
You can look up the members of myObj in several ways:
myObj.anotherProp // "another value"
myObj["some prop"] // you have to use this form if the property name has a space in it
For looping through the contents of an array, use the second form. For example, this won't work:
for (var strPropName in myObj) {
console.log(myObj.strPropName); // This won't work!
}
Instead, you should loop through the properties like this:
for (var strPropName in myObj) {
if (myObj.hasOwnProperty(strPropName)) {
console.log(myObj[strPropName]);
}
}
The if block is optional, but you'll avoid potential problems if you always include this in your code. It's also required by some validators.
Now, here's an example of an array:
var myArray = ["some value", "anotherValue"];
You access these with a numeric index:
myArray[0] // "some value"
myArray[1] // "anotherValue"
myArray[2] // undefined
And you can loop through them:
for (var index = 0; index < myArray.length; index++) {
console.log(myArray[index]);
}
You can nest objects inside arrays:
myArray = [{},{},{}];
And you can nest arrays inside objects:
myObject = {"arr1":[], "arr2":[], "arr3":[]}

Related

How to use variable content to read content of array of objects

file structure
this._formService.arraySteps[j].profile[i].nom = newValue;
where i and j are indexes
How can I make this works using variable instead of text.
I've tried the following where
tmpKeyName = "profile"
keyObject = "nom"
this._formService.arraySteps[j][tmpKeyName][i][keyObject];
Thanks
Assuming that your array/object structure is correct, your code would work:
// let's assume that this._formService.arraySteps was the following array of objects:
var arraySteps = [
{
profile: [
{nom: "something"}
]
},
{
profile: [
{nom: "something else"}
]
},
{
profile:[
{nom: "something totally different"}
]
}
];
var tmpKeyName = "profile";
var keyObject = "nom";
// Looping through that array:
for(var j = 0; j < arraySteps.length; ++j){
// Looping through the objects in the array:
for(var i = 0; i < arraySteps[j][tmpKeyName].length; ++i){
console.log(arraySteps[j][tmpKeyName][i][keyObject]);
}
}

concat JSON objects in a loop (No JQuery)

Update: Fixed mistakes in example code. Turned out my problem was caused by an additional 'records' in var jsonVar = jsonVar.concat(results.records);
How can I concat JSON objects in a loop? I can concat 2 JSON objects like this:
var json1 = {
"records": [{
"id": 28100988,
"work_text_reviews_count": 13,
"average_rating": "3.10"
}, {
"id": 10280687,
"work_text_reviews_count": 80,
"average_rating": "3.87"
}]
}
var json2 = {
"records": [{
"id": 16135639,
"work_text_reviews_count": 0,
"average_rating": "0.00"
}, {
"id": 17978337,
"work_text_reviews_count": 2414,
"average_rating": "3.76"
}, {
"id": 360721218,
"work_text_reviews_count": 4924,
"average_rating": "3.98"
}]
}
var json3 = json1.records.concat(json2.records);
To add a 3rd JSON object I know I can just add .concat(json3.records)
but how can I dynamically concatenate JSON objects in a loop?
Example:
Say values.length = 5, this means 5 JSON objects need to be concatenated.
for (var i=0; i<values.length ; i++) {
response= UrlFetchApp.fetch(url);
Utilities.sleep(1000);
var results = JSON.parse(response);
// this works now (had a typo here)
var jsonVar = jsonVar.concat(results.records);
}
You could do something like:
var jsonVar = [];
for (var i=0; i<values.length ; i++) {
results= UrlFetchApp.fetch(url);
Utilities.sleep(1000);
var results = JSON.parse(response);
jsonVar = jsonVar.concat(results.records);
}
But I am not sure if this would work because UrlFetchApp.fetch() seems to be asynchronous. This means the response is not guaranteed to be initialized to correct value if it takes more than 1000ms
A JSON object is a Javascript object. You can dynamically set the object name
for (var i=0; i<values.length ; i++) {
json[i].records.concat(json[i + 1].records)
}

iterate over json array - how to get the name / key of collection

I get a json object from an API ; I'm getting (inside another collection - but that doesn't matter) a collection of keys like so:
{ "Id": "64a66e2c-38fa-41dd-9183-8b1bd18a3c87",
"fields": [
{ "Name": "x1" },
{ "Name": "x2" },
{ "Name": "x3" }
],
"weeks": [ "2015-25", "2015-26", "2015-27" ],
"series": {
"M1": [ 6376, 17877, 22592 ],
"M2": [ 700, 702, 702 ],
"M3": [ null, 1, 1 ],
"M4": [ null, 5889, 10275 ]
}
}
the series itself (like M1) have values (1 - 1 etc) I can read and use,
but I actually need the name of the serie (like "M1").
So I iterate over the collection series and over each values within that serie without any difficulty, but how do I get the name of the serie itself - that name is (not in this example) quite descriptive and usefull
$.each(data.series, function (rowIndex, row) {
var attempt = data.series[rowIndex]; // nope this is [1,1,1,2] or something
for (var i = 0; i < row.length; i++) {
var value = row[i]; // yep this is one of the values
};
});
how do I get "serie1" into var attempt?
You already get the key as the first param when passing in a javascript object to the $.each() iterator.
$.each(data.series, function (rowIndex, row) {
window.alert(rowIndex);
});
I think what everyone is trying to say is that a more descriptive signature of the jquery.each callback is:
$.each(data.series, function (key, val) {
var attempt = data.series[key]; // nope this is [1,1,1,2] or something
for (var i = 0; i < val.length; i++) {
var value = val[i]; // yep this is one of the values
};
});
so to get what you want, simple change to:
$.each(data.series, function (key, val) {
var attempt = key;
for (var i = 0; i < val.length; i++) {
var value = val[i];
};
});

Building Array in order of income objects

I'm getting an XML and parsing it, saving it to array, the problems is that I get objects in this order:
temp1.ID = 15
temp1.name = "Dan"
temp1.phone = "32332"
temp2.ID = 12
temp2.name = "Test"
temp2.phone = 53463
temp3.ID = 2
temp3.name = "Tom"
temp3.phone = 12443
.
.
.
.
Object - its an objects that I get inside a loop while parsing XML
What I try is to save them in the same order I started to read them : Array: [temp1,temp2,temp3]
But The result of the next function is : Array: [temp3,temp2,temp1]
the function:
this.mytempect = [];
for (var i = 0; i < xml.length; i++) {
var temp = {};
temp.ID = parseXmlByTag(xml[i], "ID");
temp.name = parseXmlByTag(xml[i], "name");
temp.phone = parseXmlByTag(xml[i], "phone");
if (this.mytempect [temp .ID] == null) {
this.mytempect [temp .ID] = [];
}
this.mytempect [temp .ID].push(obj);
}
Before I save each object I check if I need to create for him a new Key or to add to existing one, in the end I get something like this:
I need to save the order in which I'm getting them so I'll save them in the order I entered them
If I understand your question here's what I think you should be doing. You seem to be confusing objects and arrays: mytempect needs to be an object if you want to store arrays against a key set by the ID.
Following your example, objects with the same key are assigned to the same array (identified by that key in the object) in the order in which they are read.
// create an object, not an array
this.mytempect = {};
for (var i = 0; i < arr.length; i++) {
var temp = {};
temp.ID = arr[i].ID;
temp.name = arr[i].name;
temp.phone = arr[i].phone;
// Don't check for null here because `this.mytempect[temp.ID]` might not exist
if (!this.mytempect[temp.ID]) {
this.mytempect[temp.ID] = [];
}
this.mytempect[temp.ID].push(temp);
}
DEMO
The demo produces an object with one object in an array under key 15, two under 12 and one under 2:
{
"2": [
{
"ID": 2,
"name": "Tom",
"phone": 12443
}
],
"12": [
{
"ID": 12,
"name": "Test",
"phone": 53463
},
{
"ID": 12,
"name": "Test",
"phone": 53462
}
],
"15": [
{
"ID": 15,
"name": "Dan",
"phone": "32332"
}
]
}
Note: you can't order the object in any way.
Perhaps you're looking for something like this
var mytempect = [],
dict = {},
i,
tmp;
for (i = 0; i < xml.length; ++i) {
tmp = {
ID: parseXmlByTag(xml[i], "ID"),
name: parseXmlByTag(xml[i], "name"),
phone: parseXmlByTag(xml[i], "phone")
};
if (!(tmp.ID in dict)) {
mytempect.push(dict[tmp.ID] = []);
}
dict[tmp.ID].push(tmp); // use fact Objects ByRef to add item
}
dict = null; // cleanup
The Array mytempect will now have indices 0, 1, 2, etc containing Arrays of all Objects which have the same ID. With your sample data you will get
mytempect[0][0].ID === 15;
mytempect[1][0].ID === 12;
mytempect[2][0].ID === 2;

How to push elements in JSON from javascript array

I want to add javascript array values into JSON values object. The other element is also replaced my element like recipients, subject, message. I got Json like:
Below is my code.
var BODY = {
"recipients": {
"values": [
]
},
"subject": title,
"body": message
}
var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
values.push(item1);
}
BODY = JSON.stringify({values: values});
alert(BODY);
I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent (because you are using jQuery/tagged) method after prepare the object from array
var BODY = {
"recipients": {
"values": []
},
"subject": 'TitleOfSubject',
"body": 'This is the message body.'
}
var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": { "_path": "/people/"+names[ln] }
};
values.push(item1);
}
// Now merge with BODY
$.extend(BODY.recipients.values, values);
DEMO.
If you want to stick with the way you're populating the values array,
you can then assign this array like so:
BODY.values = values;
after the loop.
It should look like this:
var BODY = {
"recipients": {
"values": [
]
},
"subject": title,
"body": message
}
var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
values.push(item1);
}
BODY.values = values;
alert(BODY);
JSON.stringify() will be useful once you pass it as parameter for an AJAX call.
Remember: the values array in your BODY object is different from the var values = [].
You must assign that outer values[] to BODY.values. This is one of the good things about OOP.
You can directly access BODY.values:
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
BODY.values.push(item1);
}
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Categories