Creating a list of key/value pairs in JavaScript - javascript

I need to temporarily track the state of 5 objects in JavaScript. Each of these objects has a GUID as its id. Because of this, I was hoping to create an array of key/value pairs that I can work with. The key of each pair would be the id of each object. The value of each pair would be a boolean value. My problem is, I am really not sure how to do this in JavaScript. Currently, I have the following:
var myKeyValuePairs;
var myObjects = getMyObjects();
for (var i=0; i<myObjects.length; i++) {
var id = myObjects[i].id;
// What do I do now?
}
How do I build an array of key/value pairs in JavaScript?

var myKeyValuePairs = {},
myObjects = getMyObjects(),
i, obj
for (i=0, len = myObjects.length; i < len; i++) {
obj = myObjects[i]
myKeyValuePairs[obj.id] = obj
}
Or if you really want to use an array you could do something like
var myKeyValuePairs = getMyObjects.map(function (obj) {
return {
key: obj.id,
value: obj
}
})

Related

adding an array into an array at a particular position (based on key value) in javascript

I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO

Combine object value

My jquery array is showing like
[Object { qty=1, item_id="76", add_ons="2", add_on_price:20}, Object { qty=1, item_id="76", add_ons="1",add_on_price:40}]
I want to make an array like this
[object{ qty=2,item_id=76,add_ons_price=60}]
I need to add the qty,add_ons_price in single object.
any help will be appreciated.
this will group objects based on property item_id
var result = {};
for (var i = 0, len = myObjects.length; i < len; i++) {
var obj = myObjects[i];
if (result[obj.item_id] === undefined) {
result[obj.item_id] = [];
}
result[obj.item_id].push(obj);
}
now you can add the required values and push the result in new object

Sort JSON dictionary of dictionaries alphabetically by value

I have the following dictionary of dictionaries, I have to use this format cuz I have no power over server side
{"1":{"aov":0,"oo":1,"ot":"Cem-Merve","pi":87},"2":{"aov":100,"oo":2,"ot":"Murat-Pelin","pi":88},"3":{"aov":0,"oo":3,"ot":"Fevzi-Azbiye","pi":85},"4":{"aov":0,"oo":4,"ot":"Burak-Gizem","pi":86},"21":{"aov":100,"oo":21,"ot":"Murat","pi":84,"ro":2},"22":{"aov":0,"oo":22,"ot":"Pelin","pi":83,"ro":2}}
I need to sort it with Javascript by keys alphabetically to be like
{"1":{"aov":0,"oo":1,"ot":"Cem-Merve","pi":87},"2":{"aov":100,"oo":2,"ot":"Murat-Pelin","pi":88},"21":{"aov":100,"oo":21,"ot":"Murat","pi":84,"ro":2},"22":{"aov":0,"oo":22,"ot":"Pelin","pi":83,"ro":2},"3":{"aov":0,"oo":3,"ot":"Fevzi-Azbiye","pi":85},"4":{"aov":0,"oo":4,"ot":"Burak-Gizem","pi":86}}
I've tried something like that but no hope:
function sortObject(o) {
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = o[a[key]];
}
return sorted;
}
any Ideas how can I perform that?
As others have pointed out in comments, an object's properties cannot be sorted. What you could do instead, is produce a sorted array of the objects properties, and iterate that array to access the objects properties in the order you wish. You basically already did this in your example code - you just tried to take it a step too far.
See jsFiddle
function getObjectKeysAlphabetical(obj) {
var keys = [],
key;
for (key in obj) {
if (obj.hasOwnProperty(key))
keys.push(key);
}
keys.sort();
return keys;
}
var obj = {}; //Your object here.
var keys = getObjectKeysAlphabetical(obj)
i = 0, key = null, val = null;
//Iterate the array of sorted keys.
for (i = 0; i < keys.length; i++) {
key = keys[i];
val = obj[key]; //Get the value of the property here.
}

Add values to an array

How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'
var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}
In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);
You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object
Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);

jQuery/JS: Sorting array based upon another array?

I want to sort a JSON object/array (shown below as myArray), upon values from another array - very close to the MYSQL query MYSQL WHERE IN(1,2,3). I was able to get a great answer by Nick Craver on how to sort by one property and value, but how can I do this with multiple values from my other array?
Here's my dataset Json array:
var myArray = [
{
"id":"2",
"name":"My name",
"properties":{"prop1":"value1"}
}];
And the array which I want to sort upon (serialized, coming straight from a form):
var sortArray = [ { "prop1":"value1","prop2":"value2" }];
The current sorting function as it looks right now (courtesy Nick Craver):
function filterDataset(property, value){
var newArray = [];
for (var i = 0, l = myArray.length; i < l; i++) {
if (myArray[i].properties[property] === value)
newArray.push(myArray[i]);
}
return newArray;
}
Here's how I managed to fix it:
function filterDataset2(properties){
var newArray = [];
for (var i = 0, l = dataset.length; i < l; i++) {
$.each(properties, function(){
if (dataset[i].properties[this.name] === this.value)
newArray.push(myArray[i]);
});
}
return newArray;
}
This may not be what you mean, but if you have a known list of properties, could you just || your comparison? Say you have 2 properties...
function filterDataset(property, value){
var newArray = [];
for (var i = 0, l = myArray.length; i < l; i++) {
if ((dataset[i].egenskaper[property1] === value) || (dataset[i].egenskaper[property2] === value) )
newArray.push(myArray[i]);
}
return newArray;
}
Otherwise if the length of the sorting array is unknown you could use a array.find type method that will return true if the property is found within the array in question. If it returns true, just push that value on your newly sorted array.

Categories