Getting values of an object after iteration - javascript

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);
}

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
}));
}

How to create dynamic object attributes from Ajax response in 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
}

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);

How would you count the instances of objects in arrays within an array

So, essentially I am getting a set of records as an array of objects like
[{name: tyler, categories: ["friends", "neighbor"]}, {name: joe, categories: ["friends"]}].
and I want to count the contents of the internal array instances. So in this example, the return would be friends: 2 and neighbor: 1. As some background info, I am getting a collection of records from mongo within the meteor framework. I am then using fetch() to convert these records to an array of objects like above. I then want to use these objects to create a pie graph based on the counts of the specific instances of each object within the inner array of each object (these objects would be the ones returned by the db query) within the outer array.
You can write a simple function to count your categories counts and store the result in a dictionary of key/value pairs.
function countCategories(docs){
// accumulate results inside a JS object acting as a key/value dict
var result = {};
docs.forEach(function(doc){
doc.categories.forEach(function(category){
// initialize count to 0 when a new key is found
if(_.isUndefined(result[category])){
result[category] = 0;
}
// increment the corresponding count
result[category]++;
});
});
return result;
}
Given the sample data in your question, this function will return :
Object {friends: 2, neighbor: 1}
EDIT :
You can then convert this dictionary to an array of objects.
function convertToArray(dict){
var result = [];
_.each(dict, function(value, key){
var object = {
category: key,
count: value
};
result.push(object);
});
return result;
}
Using underscore and reduce:
result = _.reduce( data, function( counter, o ) {
_.each( o.categories, function(c){
counter[c] = 1 + _.result(counter, c, 0);
});
return counter;
}, {});
Demo in this fiddle
reduce goes through your array (first arg) and applies
the function you give it (second arg) and a starting value for
the memo (third arg). This memo is passed to each call to
your function as the first argument, you can us it to store
stuff you want to remember.
I've set the starting value for the memo to be an empty object
which we will use as a counter.
result = _.reduce( data, function( counter, o ) {
// current element of the array: o
// stuff you want to remember for: counter
return counter;
}, {});
You might attach a function to the array and count the elements inside of it.
yourArray = [1,2,3];
yourArray.countElements = function(){
var elements=0;
for(x=0;this[x]!=undefined;x++){
instances++
}
return instances;
};
yourArray.countElements(); // outputs 3
Modify this, using "neighbors" and "friends" instead of "elements" and counting them only if this["categories"]["the_category"] is different of undefined.
Also you could attach it to Array.prototype

Undefined value after conversion from JSON array to object

I have JSON array with one object consisting of nodes and links.
data = [Object]=[ { nodes: Array[..] ,links: Array[…] } ]
This is all fine, but for accessing the links for example I have to use data[0].links, which is a bit annoying. I would like the array to be an object, so that data.links gives access to the links. I have tried to set:
data = data[0];
But then the array of Objects, data.links, are displayed as "undefined".It seems like when a specific element is accessed the value is displayed, for example data.links[3].name. Why is that?
Edit:
More specifically:
if data = [ { nodes: Array[... ] ,links: Array[...] } ] =>
console.log(data[0].links); //shows the data[0].links[0].name = value in the console
if data = { nodes: Array[... ] ,links: Array[...] } =>
console.log(data.links); //shows data[0].links[0].name = undefined
but interestingly
console.log(data.links[0].name); //shows the correct value.
A couple of solutions:
If you control the JSON output, simply remove the enclosing brackets [] those are basically wrapping your object in an array.
data = { nodes: [...] ,links: [...] };
If you don't control the JSON just simply assign the zero index of the array to the variable you actually want to work with.
json = [ { nodes: [...] ,links: [...] } ];
data = json[0];
Unfortunately, 'links' is an array. To access a member of that array, you will need to access its index value.

Categories

Resources