JavaScript: how can we push an array inside an array? - javascript

I am facing an issue in small requirement. I want to create a JSON array in below format using JavaScript for loops.
var payloadTest = {
"people": [{
"pic": "sap-icon://employee",
"name": "Ravi",
"role": "team member",
"appointments": [{
"start": new Date("2017", "0", "21", "0", "0"),
"end": new Date("2017", "0", "21", "23", "59"),
"title": "Meet John Miller"
}, {
start: new Date("2017", "0", "18", "0", "0"),
end: new Date("2017", "0", "18", "23", "59"),
title: "Team meeting",
}]
]
}
};
Im trying with below code using for loops. But it is not working.
var itemsArr = [];
var headArr = [];
for (var i = 0; i < resultSet.length; i++) {
var obj = {};
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
headArr.push(itm);
obj.start=resultSet[i].Begda;
obj.end=resultSet[i].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
//headArr.push(itemsArr);
}
payloadTest.people = headArr;
payloadTest.people.appointments = itemsArr;
Can someone please help me to create an array using for loops in the above JSON Format.
Note :: appointments array count may increase based on the results coming from backend

In:
payloadTest.people.appointments = itemsArr;
you are trying to assign the appointment array as a property of an array of people. Instead, you should be assigning it as a property of an (or every?) individual person.
So you could do:
payloadTest.people[0].appointments = itemsArr;
but that would only give one of the people an array of appointments. It's unclear from your code whether you want each person to have a reference to (or copy of) the same appointment array, one person to have it, or whether you thought you were creating separate arrays for each person. To do the later, you'd need a nested loop.
Update
You probably want to move the declaration/initialization of itemsArr inside the loop, so that each person has their own array (otherwise, modifications to one person's appointment array would be made to everyone's array).
Then, you would likely want to initialize them with a unique test array - so a nested loop (say j from 0 to i), creating incrementally larger lists of appointments for each person. But as it's just test data you're creating, it's really up to you what belongs in there.

Change your code according to below code
for (var i = 0; i < resultSet.length; i++) {
var obj = {};
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
headArr.push(itm);
obj.start=resultSet[i].Begda;
obj.end=resultSet[i].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
itm.appointments = itemsArr; // Added
//headArr.push(itemsArr);
}
payloadTest.people = headArr;
/*payloadTest.people.appointments = itemsArr;*/ // Removed
Removed
payloadTest.people.appointments = itemsArr;
Because it assigns appointments to person array not to each person. You have to add appointments to each person record to added in loop
itm.appointments = itemsArr;
See below snippet for your multiple appointment. I used dummy data.
Change according to your data format.
var headArr = [];
var payloadTest = [];
var resultSet = [{'Rowlabel' : 'Ravi', 'RowId' : 'team member', 'appointments' :[{'Begda' : 'test', 'Endda' : '1'}, {'Begda' : 'test', 'Endda' : '1'}]}, {'Rowlabel' : 'name', 'RowId' : '1', 'appointments' : [{'Begda' : 'test', 'Endda' : '1'}]}];
for (var i = 0; i < resultSet.length; i++) {
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
var itemsArr = [];
for (var j = 0; j < resultSet[i].appointments.length; j++) {
var obj = {};
obj.start=resultSet[i].appointments[j].Begda;
obj.end=resultSet[i].appointments[j].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
}
itm.appointments = itemsArr; // Added
headArr.push(itm);
}
payloadTest.people = headArr;
/*payloadTest.people.appointments = itemsArr;*/ // Removed
console.log(headArr);
Hope it helps.

Related

Iterating and printing a JSON with no initial key and multiple entries

How would you go about iterating through a JSON object no initial key but multiple entries?
var json_no_key =
{
{"txid" : "1",
"amount" : "100",},
{"txid" : "2",
"amount" : "50"},
};
I have tried using other methods whereby each element would have a key itself such as
for(var i = 0; i < transaction.vin.length; i++)
{
var my_json = transaction.vin[i];
console.log(my_json[i])
for(var j = 0; j < my_json.length; j++)
{
console.log(my_json[j]);
}
}
but this relies on there being an initial key.
The reasoning for this format is due to the nature of how a api outputs data.
I echo with #CherryDT. The object json_no_key is not a valid JSON format. Please check the format in https://jsonlint.com/. Instead of an object, convert it into an array so that you could do the following using a simple forEach:
const a =[
{
"txid": "1",
"amount": "100",
},
{
"txid": "2",
"amount": "50"
},
];
a.forEach(element=>{
console.log(element.txid);
console.log(element.amount);
})

Multicombox is not displaying tokens when value is selected from it

I have one array of data and I want to bind that data to multicombobox.
I have binded that data to Multicombobox using javascript as shown below.
The problem is when I select any value from multicombobox, tokens are not displaying as per the default behavior of the control.
Please help me in this. As per my guess, this array is not associative array (do not have keys and values.) this might have caused this issue.
Below is the code:
var data = sap.ui.getCore().getModel("myModel").getData();
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
this.getView().setModel(oModel, "myModel");
var fruitsArray = data.fruits[0].names;
for(var i = 0; i<fruitsArray.length; i++){
var fruitsDD;
if(!fruitsDD){
fruitsDD = this.getView().byId("MCBId");
}
var oCoreItem = new sap.ui.core.Item();
oCoreItem.setText(fruitsArray[i]);
oCoreItem.setKey(fruitsArray[i]);
fruitsDD.addItem(oCoreItem);
}
{
"A":"Apple",
"B":[
{
"key":1,
"value":"ball",
"fruits":[
"Apple",
"Orange",
"banana",
"Guava"
]
}
]
}
XML view:
<MultiComboBox id="MCBId" width="280px" class="sapUiTinyMarginTop" ></MultiComboBox>

JavaScript nested for-loop to add values to an object

I have encountered a situation in my code where I have three java script variables in which two are arrays and one is a single string variable. The following are their structure:
var selectedUser = $('#Employees_SelectedValue').val(); //It has one one value "12121"
var selectedCountries = $('#Countries_SelectedValue').val(); //It has multiple values ["IND", "USA"]
var selectedSourceSystems = $('#SourceSystems_SelectedValue').val(); //It has multiple values ["SQL", "ORACLE", "MySQL"]
What I have to do is to add these values in a class on the basis of selectedUser such as User is same for all the values but the remaining two are different as:
var userSettings = { userName: selectedUser, userCountry: selectedCountries, userSourceSystem: selectedSourceSystems };
The situation is to add the values from this class into an array in such a way that every userCountry and userSourceSystem will come as a single entity such as:
{ userName: "12121", userCountry: "IND", userSourceSystem: "SQL" },
{ userName: "12121", userCountry: "USA", userSourceSystem: "ORACLE" },
{ userName: "12121", userCountry: "", userSourceSystem: "MySQL" }
I'm trying the approach of nested-for loop to handle this scenario like:
for (var i = 0; i < selectedCountries; i++)
{
for (var j = 0; j < selectedSourceSystems; j++)
{
userSettings.userName = selectedUser;
//Add i and j values
}
}
Please suggest an effective approach other than this.
You may set up a 3×n matrix ( a 2d array) and rotate it by 90 degrees:
var matrix = [[selectedUser],selectedCountries,selectedSourceSystems];
var result =
Array(//set up a new array
matrix.reduce((l,row)=>Math.max(l,row.length),0)//get the longest row length
).fill(0)
.map((_,x)=> matrix.map((row,i) => row[i?x:x%row.length] || ""));
Result
If result should contain objects, then map the 2d array to objects:
var objects = result.map(([a,b,c])=>({userName:a,userCountry:b,userSourceSystem:c}));
result
Small explanation:
row[i?x:x%row.length] || ""
Actually does the following:
If were in the first row ( i=0 ) ("12121")
take whatever value of the array (x%row.length), so basically always "12121"
if not, try to get the value of the current column(x)
if row[x] doesnt exist (||) take an empty string ("")
A more basic approach:
var result = [];
for(var i = 0,max = Math.max(selectedCountries.length,selectedSourceSystems.length);i<max;i++){
result.push({
userName:selectedUser,
userCountry:selectedCountries[i]||"",
userSourceSystem:selectedSourceSystems[i]||""
});
}
result
I believe it would be better to restructure your userSettings object in more natural way:
userSettings: {
name: "userName",
countries: ["USA", "IND"],
userSourceSystems: ["MySQL", "Oracle"]
}
Then you can fill it with settings from your inputs like this
for (item in selectedCountries)
userSettings.countries.push(item)
for (item in selectedCountries)
userSettings.userSourceSystems.push(item)

How to prevent default sorting in key value array Javascript

I have this array:
recentPageArray = {
"e49f8a67-3075-433a-bacd-30379008fdb2": {
"id": "e49f8a67-3075-433a-bacd-30379008fdb2",
"name": "afolder",
"type": "indexfolder"
},
"3a1ca419-5467-4662-9f7a-f3e9246a1d49": {
"id": "3a1ca419-5467-4662-9f7a-f3e9246a1d49",
"name": "folder1",
"type": "indexfolder"
},
"832f9d4e-297e-40e9-9189-75ce3b86341a": {
"id": "832f9d4e-297e-40e9-9189-75ce3b86341a",
"name": "afolder",
"type": "documentfolder"
},
"86fee1ce-21cd-4948-bf9d-a6c81b897a0e": {
"id": "86fee1ce-21cd-4948-bf9d-a6c81b897a0e",
"name": "afolder",
"type": "documentfolder"
}
}
Whenever I push new array in the this array. Key sort automatically. I dont want to sort array in the key base. I need new pushed key item in top of the array.
I suggest you to mantain 2 references:
1 Array (list)
1 Object (key, value)
The Object (key->val) cannot mantain the elements' insert order (and if an utopic new browser implementation want to order in descending order(for any cause) your code will be sensible to it).
So, while populating the object,also push the element key in the Array.
When you want to iterate use the Array to iterate in order (and it is also faster)
myObject = {};
myArray = [];
/** POPULATING **/
for (var x in myData){
myObject[myData[x].key] = myData[x].value;
myArray.push(myData[x].key);
}
/** ITERATING **/
for (var y =0; y < myArray.length; y++){
var readingKey = myArray[y];
var storedData = myObject[readingKey];
//your code here
}
Regards

How to use loop to create obj in javascript

My aim is to create something like this
$rootScope.customMarkers = [
{address: "1600 pennsylvania ave, washington DC", "class": "my1"},
{address: "600 pennsylvania ave, washington DC", "class": "my2"},
];
Here is part of my code, yet this does not work
for (var i = 0; i < cart.length; i++) {
$rootScope.customMarkers = [{
address: cart[i].address,
"class": cart[i].class,
}];
}
Could anyone give me some clues or just give me some key words?
This code will not work since you have to push objects to array:
$rootScope.customMarkers = [];
for (var i = 0; i < cart.length; i++) {
$rootScope.customMarkers.push({
address: cart[i].address,
"class": cart[i].class,
});
}
Your current code overwrites $rootscope.customMarkers on each loop iteration with a new array containing just one entry.
This is a classic use of map:
$rootScope.customMarkers = cart.map(function(entry) {
return {address: entry.address, class: entry.class};
});
...assuming cart is an array. If it isn't, it's just array-like, you might use Array.from:
$rootScope.customMarkers = Array.from(cart, function(entry) {
return {address: entry.address, class: entry.class};
});
...or a boring old loop:
$rootScope.customMarkers = [];
for (var i = 0; i < cart.length; ++i) {
$rootScope.customMarkers[i] = {address: cart[i].address, class: cart[i].class};
}
Side note: As of ES5, both uses of class above are valid, you don't have to put quotes around one but not the other. If you need to handle old engines that may not handle it, you need to handle it in both places: "class": entry["class"].
You can simply use foreach loop for angularjs
angular.forEach(cart, function(value, key) {
$rootScope.customMarkers.push({
address : value.address,
class : value.class
});
});
It's done.

Categories