Add to javascript associative array - javascript

I want the following structure:
var data={"users":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
},
{
"firstName":"John",
"lastName":"Jones",
"joined":2010
}
]}
I want to be able to programatically add entries to it.
Here is what I tried:
var data = [];
data.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});

Your array is actually data.users, not data.
So use this instead:
var data = {users: []};
data.users.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});

var data = {users: []};
data.users.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});

Your data object contains one property, users, which is an array of users, so you need to push into it:
data.users.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});

Related

JSON.parse in Javascript disorder select

I receive from api a Json like this:
{
"paises":{
"145":"CHINA (53)",
"150":"ESPAÑA (45)",
"68":"HOLANDA (38)",
"236":"RUMANIA (52)"
}
}
List of countries always alwais is order alphabetic but when add to a select list show in disorder and order by id.Like this:
"68":"HOLANDA (38)",
"145":"CHINA (53)",
"150":"ESPAÑA (45)",
"236":"RUMANIA (52)"
This is a code:
var datos = JSON.parse(data);
$.each(datos.paises, function(id, valor) {
$("#informe-id").append($('<option>', {
value: id,
text: valor,
}));
});
In my project I have this problem in more selects. In other list size is greater that 200, so that parse and short maybe it consumes a lot of resources.
What is the best way to populate select keeping list in alphabetic order?
Thank a lot
You can use Object.entries to convert the object into array. Use sort to sort it.
Note: orderedDatos will be an array now and not an object. You might need to change something on your $.each
var data = '{"paises": {"145": "CHINA (53)","150": "ESPAÑA (45)","68": "HOLANDA (38)","236": "RUMANIA (52)"}}';
var datos = JSON.parse(data);
var orderedDatos = Object.entries(datos.paises).sort((a, b) => a[1].localeCompare(b[1]));
$.each(orderedDatos, function(id, valor) {
console.log(valor[0], valor[1]); //Use valor[0] to get the key | Use valor[1] to get the value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Doc: Object.entries(), sort()
You could use Object.entries() it will return an array then you can use sort() method array using String.localeCompare() to get the required result.
DEMO
var datos = {
"paises": {
"145": "CHINA (53)",
"150": "ESPAÑA (45)",
"68": "HOLANDA (38)",
"236": "RUMANIA (52)"
}
};
let paises = Object.entries(datos.paises).sort((a,b)=>a[1].localeCompare(b[1]));
$.each(paises, function(index, value) {
$("#informe-id").append($('<option>', {
value: value[0],
text: value[1],
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="informe-id"></select>

Seperate Objects in local storage Javascript

I currently have an item in local storage which looks like this
"cars":[
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}
I want to retrieve all of the Id's only and store them in a string.
At the minute I am pulling the data like this:
var cars = "";
cars= localStorage.getItem('cars');
var carArr= new Array();
carArr.push(cars);
How can I just obtain the Id's
If i understand your question correctly, you have to use Array.map to transform your array in combination with JSON.parse and JSON.stringify to read/write from the storage.
Here is an example using a "mocked" localStorage:
// use a mock storage because snippet doesn't allow localStorage usage.
var mockStorage = {};
// setup initial storage
try {
mockStorage.cars = JSON.stringify([
{
Id:7,
Name:"Audi",
},
{
Id:8,
Name:"Ford",
}
]);
} catch(e) {}
console.log('inital local storage:\n', mockStorage);
// example
var cars = [];
// parse JSON string value from storage to javascript object.
try {
cars = JSON.parse(mockStorage.cars)
} catch(e) {}
console.log('cars:\n', cars);
// transform array of cars to array of car ids
var ids = cars.map(car => car.Id)
console.log('car ids:\n', ids);
// transform array to JSON string
try {
mockStorage.cars = JSON.stringify(ids);
} catch(e) {}
console.log('local storage:\n', mockStorage);
localStorage only supports strings. So, you have to use JSON.parse to get the cars array from string and then use array#map to get all the ids.
var carsString = localStorage.getItem('cars');
var cars = JSON.parse(carsString);
var ids = cars.map( car => car.Id);
console.log(ids);
Use this,
//you get this from localStorage after you parse it
//JSON.parse(localStorage.cars);
var cars = [
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}];
var res = [];
cars.forEach(function(val){
res.push(val.Id);
});
console.log(res);

loop over array and add separate objects to new array - only one item in new array

I am making a call to a backend API which returns a JSON response. I have read a number of answers on here including this but they dont seem to cover my issue.
The JSON response from the API looks like this:
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
}
]
My Angular JS code looks like this:
controller.testDetailHolder = [];
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder.name = data[i].name;
controller.testDetailHolder.id = data[i].id;
}
});
When I console.log controller.testDetailHolder it only shows the second value from the GET request (i.e. the array just holds one value) however, I want the controller.testDetailHolder to look like this:
controller.testDetailHolder = [
{
id: "1",
name: "test1",
},
{
id: "2",
name: "test2",
}
]
Any assistance with this would be greatly appreciated.
Thanks.
controller.testDetailHolder = [];
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder.push({
name : data[i].hours,
id : data[i].id
});
}
});
Your loop is constantly overwriting controller.testDetailHolder, so you need to use array syntax:
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder[i].name = data[i].hours;
^^^
controller.testDetailHolder[i].id = data[i].id;
}
});
You can assign the data like:
Test.getAllTests.query({}, function(data){
controller.testDetailHolder = data;
});
Or use push to add it to the existing array:
Test.getAllTests.query({}, function(data){
Array.prototype.push.apply(controller.testDetailHolder, data);
});
controller.testDetailHolder is the array itself, not an element within the array. You want to add the values as elements, which is accessed by controller.testDetailHolder[i], where i is the index of the element. Modify your code to be:
controller.testDetailHolder[i].name = data[i].hours;
controller.testDetailHolder[i].id = data[i].id;
The problem is that you are completely overwriting the complete testDetailHolder array, because you do not specify an index when setting the values.
controller.testDetailHolder.name should be controller.testDetailHolder[i].name
Another issue is that you are using data[i].hours when hours is not defined on the JSON.
Lastly since you want to copy the whole object you could just do a single assignment
Test.getAllTests.query({}, function(data){
controller.testDetailHolder = data;
});

javascript dynamic structure with array or object

Im trying to create a structure with Javascript as follows:
var users = {
user.id: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
user.id2: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
};
What i need: add new sessions and remove them, removing okay, but how should i define object and how can i push new sessions to user obejct? That's why key is equal to value.
If you want to use session.id1 instead of something like sessionId1 :
Assign value:
users['user.id'].['session.id1'] = value;
Create object:
var users = {
'user.id': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
'user.id2': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
};
But I don't recommend it. If you are the only one who is gonna work with this code, it's ok.
You can first create an empty object and fill it as and when the data comes like
users[user.id] = {};
For an example:
var users = {};
var user = {id : 1}; //Data received(Just an example)
users[user.id] = {};
var session = {id1 : 1.1}; //Data received
users[user.id][session.id1] = session.id1;
console.log(JSON.stringify(users));
How about refactoring the user object to store sessions as an array and push, pop and slice them as required.
var users = [
{
id:'userid',
sessions: [
{
id: 'sessionid',
sessiondata: something
},
{
id: 'sessionid',
sessiondata: something
}
]
}];
This way to can just use normal array operators on the session array for each user.

Remove one level of nested arrays from JS data structure

How can I convert the following data structure:
var data = [ [ { time: 1, speed : 20 } ] ];
to
var data = [ { time: 1, speed: 54 } ];
I just want to remove the array.
As the data is an array, you just want to select the first element of the outer array
so the solution would be
var data = [[{time:1,speed:20}]]; // Or whatever the data is
data = data[0];
Or if you're accessing the data via another object
var data = yourObject[0];
Try this :
JSON.stringify(data).substr(1,JSON.stringify(data).length-2);

Categories