How to create dynamic object attributes from Ajax response in Javascript - javascript

I'm using Ajax in order to get a list of items of an inventory, I would like to have an object named inventory and then create attributes named as the items of the response, so that means if I insert more items in my database I wouldn't need to hard code the elements of the object in my javascript file. Right now I'm able to create the object, but I can't access de dynamically created attributes and their values. I would like to alter the values with some user Input like pressing a button.
I've tried to use a Dictionary and searched but that didn't seem to work
var inventory = {};
$.ajax({
url:"phpf/getItems.php",
type:"POST",
data:{},
success: function (data) {
var result = JSON.parse(data);
for (var index = 0; index < result.length; index++) {
var str = String(result[index][0]);
inventory[str] = 5;
}
}
});
console.log(inventory["Cookies"]);
console.log(inventory[0]);
I would like to access the information of the object like inventory["something"] but console says it's undefined, and when I try to add the value to another number it says NAN as result

You can already access your data parsed from your JSON.parse, it returns an object so it can be called using the ['key'] accessor :
let json = '{"key1": 2, "key2": "test"}';
let values = JSON.parse(json);
console.log(values.key1);
console.log(values['key2']);

Inventory is an object, so you want to access keys and values in your object using dot notation.
let inventory =
{
item1: "Cookie",
item2: "Cake"
}
inventory.item3 = "Brownies";
console.log(inventory.item1);
console.log(inventory.item2);
console.log(inventory.item3);
Also to loop through an object you want to go like so:
for (var key in object) {
//your code here
}

Related

How to make list of object by storing in an array

I am fetching some data from my firebase database and structuring the data in an object and storing each object in an array but it is only storing the 1st object multiple times and not storing 2nd 3rd ... or Nth object I am using a loop for storing them but can't figure out what is wrong please look into the function below
function dataHandler(deviceList,roomList) {
var data = {
roomName: "",
devicesAssigned: [] ,
};
for (let i = 0; i < roomList.length; i++) {
data.devicesAssigned = deviceList[i];
data.roomName = roomList[i];
console.log(data);//printing object getting from database
dataArray.push(data);// storing each object in an array
}
console.log(dataArray);// printing after array is filled
}
this is the output I am getting please notice that I am successfully fetching different objects from my database but it's not pushing all of them its only printing object number 1 twice
To understand what the issue here is, you got to know the difference between References and Values.
In Javascript Object and Arrays are stored into memory by their reference.
Where as Primitive datatypes such as Number, String, Boolean are stored by value.
Lets say I am creating an Object as
myObj = {firstName: "First", lastName: "last"}
In this case myObj will store the memory reference of myObj and not the value.
If you assign this object to another variable, it will not copy the value of object, instead you are only copying the reference to another variable.
copyObj = myObj
The following operation will not only change copyObj but myObj as well becuase both variable are pointing to exact same Object (Hash map) in memory.
copyObj.firstName = "New First Name
Now coming to your problem
for (let i = 0; i < roomList.length; i++) {
data.devicesAssigned = deviceList[i];
data.roomName = roomList[i];
console.log(data); //printing object getting from database
dataArray.push(data); // storing each object in an array
}
Your for loop is pointing to the same data object, assigning some values to it and pusing it into the array.
In first Iteration it will update data object and push it into array. (Remember that it will only push the reference).
In 2nd and subsequent iteration, you are only updating already existent data object and not creating a new one hence all the variables in your array pointing to same data object will have same value.
Creating a new Object (a new reference to a new HashMap) every time inside the array will resolve your issue.
for (let i = 0; i < roomList.length; i++) {
const data = {};
data.devicesAssigned = deviceList[i];
data.roomName = roomList[i];
console.log(data); //printing object getting from database
dataArray.push(data); // storing each object in an array
}
I would really suggest you to read a Article on Copying objects and arrays.
Also Shallow copy vs Deep Copy.
You're pushing the same data object onto the array every time. You need to create a new object each time through the loop.
function dataHandler(deviceList, roomList) {
for (let i = 0; i < roomList.length; i++) {
var data = {
roomName: roomList[i],
devicesAssigned: deviceList[i],
};
console.log(data); //printing object getting from database
dataArray.push(data); // storing each object in an array
}
console.log(dataArray); // printing after array is filled
}
You can also get rid of the for loop and do it all in one call to map().
dataArray = roomList.map((room, i) => ({
roomName: room,
devicesAssigned: deviceList[i]
}))
You are using the same object in the loop. Use the following code to get it working:
let roomList = ['r1', 'r2', 'r3'];
let deviceList = ['d1', 'd2', 'd3'];
const data = dataHandler(deviceList, roomList);
console.log(data);
function dataHandler(deviceList, roomList) {
return roomList.map((room, i) => ({
devicesAssigned: deviceList[i],
roomName: room
}));
}

convert json values in comma separated string using javascript

I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);

Getting values of an object after iteration

I have this object i copied from my console
Object { input_name: "hi", input_type: "world", input_number: "200" }
which i had earlier put together this way
var post = {
input_name: name,
input_type: type,
input_number: number
};
console.log(post);
I am passing the data as an array to another function which does the inserting to a mongodb. I need to get the first,second and third values in seperate variables in order to be inserted into the database.
I have tried this
for (var key in post) {
var one = post[key];
console.log(one);
break;
}
and have only just got the first value. How can i hold the three values each in its own variable?.
You don't need to have new variable per each value. Just access object properties by it's keys:
console.log(post.input_name);
console.log(post.input_type);
console.log(post.input_number);
remove the break from your loop.. your code should be:
for (var key in post) {
var one = post[key];
console.log(one);
}

localStorage Array split

I have a script to put formdata into localStorage. The data saved in an array. I want that the elements in the array where list without brackets and underneath eachother. Does somebody have a hint for me how to do that?
The array and the output in the div looks like this:
[[{"EMail":"testmail#test.com","Salutaion":"Mr","FirstName":"Test","Name":"Testname"},{"EMail":"testy#test.com","Salutaion":"Mrs","FirstName":"Testy","Name":"TestyFemale"}]]
The script to show the array in a div:
var output = '';
for (var key in localStorage) {
output = output+(key + ':' +localStorage[key])+'\n';
}
$('#divtoshowarray').html(output);
https://jsfiddle.net/6x490kot/
Here is the updated code
$(document).ready(function() {
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var output = '';
var objectFromLS = JSON.parse(localStorage.getItem('testObject'));
for (var key in objectFromLS) {
if (objectFromLS.hasOwnProperty(key)) {
output = output+(key + ':<br>' +objectFromLS[key])+'\n';
}
}
$('#divtoshowarray').html(output);
});
Key Points
You want to iterate on testObject data stored in localStorage. So you need to get testObject from localStorage and iterate on it. Please note, localStorage.getItem will return string, so, you need to parse it so as to return a JSON.
Then you need to iterate on the object, to paint key value pair.
For reference - https://jsfiddle.net/6x490kot/1/

Convert array of javascript objects to JSON

I have a set of data in the format:
[{"title":movietitle1, "id":445, "release":"16JUN1985"}, {"title":movietitle2, "id":487, "release":"12AUG1993"}]
Which I need to convert into JSON formatted as such:
{
"movietitle1":{"id":445,"release":"16JUN1985"},
"movietitle2":{"id":487, "release":"12AUG1993"}
}
I don't have any idea of how to make this happen.
You can do this with JSON.stringify() and some basic data manipulation.
Store your data in a variable, lets call it input_data.
Loop through your data and use each entry to build up another variable, lets call it output_data.
// create an object to store the newly formatted data
var output_data = {};
// the code in here is run once for each item in input_data
for (var i = 0; i < input_data.length; i++) {
// get the current item's title
var title = input_data[i].title;
// use the title as the key in the output data
// and assign the other values to that key
output_data[title] = {
id: input_data[i].id,
release: input_data[i].release
};
}
// use JSON.stringify() to make a valid JSON string
var json = JSON.stringify(output_data);
// now use the variable json which contains your JSON string
What you are asking for is to turn an array into a map , keying by a specific property, If you really want JSON, you can just call JSON.stringify on the resulting JS object.
http://jsfiddle.net/FfE8f/1/
/**
* Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
* This method supports nested lists
* Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
* Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
* #param {object[]} list of objects to be transformed into a keyed object
* #param {string} keyByProp The name of the property to key by
* #return {object} Map keyed by the given property's values
*/
function mapFromArray (list , keyByProp) {
var map = {};
for (var i=0, item; item = list[i]; i++) {
if (item instanceof Array) {
// Ext.apply just copies all properties from one object to another,
// you'll have to use something else. this is only required to support nested arrays.
Ext.apply(map, mapFromArray(item, keyByProp));
} else {
map[item[keyByProp]] = item;
}
}
return map;
};
console.log(mapFromArray([
{"title": "title 1", "id":445, "release":"16JUN1985"},
{"title":"movietitle2", "id":487, "release":"12AUG1993"}],
"title"
)));
// outputs
{
"title 1": {"title":"title 1","id":445,"release":"16JUN1985"},
"movietitle2": {"title":"movietitle2","id":487,"release":"12AUG1993"}
}
See More efficient way to search an array of javascript objects?
Your mixing terms. I'm assuming you're asking about manipulating data with JavaScript objects and not strings with JSON data. (The later can be converted with JSON.parse).
First iterate over the array and assigning to an object. This kind of data manipulation works well using Underscore, check it out.
In vanilla JS lets try something like this:
var newData = {};
data.forEach(function(item) {
var title = item.title;
delete item.title;
newData[title] = item;
});
A little crufty but gets the job done.
Personally I'd use this Underscore version:
var newData = _(data).chain()
.map(function(item) {
return [item.title, _(item).omit('title')];
})
.object()
.value();

Categories

Resources