variable name is appended to json instead of variable value - javascript

I get a json from an API I wrote. This json contains some values and one of this should be appended to another json.
The json to append the data to is the following:
originalOrder = {
"nome": 1,
"cognome": 2,
"mail": 3,
"telefono": 4,
"cf": 5,
"data": 6,
"ora": 7,
"cellit": 8,
"cellex": 9
};
The data I need to append is:
var toAppend = data.name;
and if i echo the toAppend value it shows the correct value. Say for example that toAppend echoes dummyData. I want the json to be at the end:
originalOrder = {
"nome": 1,
"cognome": 2,
"mail": 3,
"telefono": 4,
"cf": 5,
"data": 6,
"ora": 7,
"cellit": 8,
"cellex": 9,
"dummyData": 10
};
So I also calculate the length of the array:
var lunghezza = parseInt(originalOrder.length);
lunghezza = lunghezza +2;
and then I add the new item to the array:
originalOrder.toAppend=lunghezza;
but the array ends up like this:
originalOrder = {
"nome": 1,
"cognome": 2,
"mail": 3,
"telefono": 4,
"cf": 5,
"data": 6,
"ora": 7,
"cellit": 8,
"cellex": 9,
"toAppend": NaN
};
so I have two issues:
i get the variable name instead of the variable value
I get not a number instead of 10 (I tried also to force it with parseInt but seems with no luck)
What am I doing wrong here?
Edit:
if I do
var toAppend = data.nome;
console.log('toAppend: '+toAppend);
in console.log:
toAppend: dummyData;
that is the expected behaviour
Thanks!

originalOrder is an object and for this reason, to get the number of keys (i.e., "the length of the object"), you need:
Object.keys(originalOrder).length
To add a key with the value of the var toAppend you need to write:
originalOrder[toAppend] = lunghezza

To use variable value as a key to an object you can use the square bracket in javascript.
const obj = {
"hello": "world"
};
const key = "value";
obj[key] = "any value";
console.log(obj)
will print
{
"hello": "world",
"value": "any value"
}
Also, you can't use length properties on an object. However, you can get list of keys of an object, then get the length.
console.log(Object.keys(obj).length);
will print
2
Hope this helps

Related

How to use filter method for string key

I am new to this kind of problem.
I am getting an array object like this:
const obj = [{
"adId": 6,
"receiverid": 5,
"senderId": 7
},
{
"adId": 7,
"receiverid": 6,
"senderId": 5
}
]
console.log(obj.filter(item => item.adId > 5))
Now I want to apply filter method to apply some conditions over it.
I applied filter() method but the error comes that says
filter is not a function
But I am not getting how to apply filter for this kind of object data.
Suppose, you have this object that you mentioned
const obj = [
{"adId":6,"receiverid":5,"senderId":7},
{"adId":7,"receiverid":6,"senderId":5}
];
If I correctly understood your question, now you want to filter only some of the object that fit according to your condition, so for that you apply filter like this
const filteredObjects = obj.filter((individualObject) => {
if (individualObject['adId'] > 6) {
return true;
}
});
so now our filteredObjects will be an array like below
filteredObjects = [{"adId":7,"receiverid":6,"senderId":5}]
This code works. A couple of things though. The data type is an array of objects, not an object, and your filter condition didn't filter out either object. If you change it to item.adId > 6 it will.
const arr = [{
"adId": 6,
"receiverid": 5,
"senderId": 7
},
{
"adId": 7,
"receiverid": 6,
"senderId": 5
}
]
console.log(arr.filter(item => item.adId > 6))

How to create a 3D array to json and parse it?

I try to combine 2 tables of database to a json object, I think it is maybe a 3D array
like this↓
table_1 ->(name:"Ken"),(gender:"male")
table_2 ->(name:"Lon"),(gender:"male")
table_1 and 2 is 1st dimension, name and gender is 2nd dimension,
ken and male is 3rd dimension
so, I made a json object wiht PHP "json_encode()", and try to parse it with javascript
json object:
{
"client_infos":[ {
"client": {
"no": 1, "C_name": "ken", "input_date": "2017-07-20 13:44:46", "total_price": 123
}
,
"item_lists":[["item_list",
{
"no": 1, "rs_no": 1, "item_name": "ApplePie", "item_quantity": 2, "unit_price": 10
}
],
["item_list",
{
"no": 2, "rs_no": 1, "item_name": "BananaCow", "item_quantity": 3, "unit_price": 5
}
]]
}
,
{
"client": {
"no": 3, "C_name": "ken", "input_date": "2017-07-20 14:24:26", "total_price": 200
}
,
"item_lists":[["item_list",
{
"no": 5, "rs_no": 3, "item_name": "LimeMilk", "item_quantity": 5, "unit_price": 33
}
]]
}
]
}
how do I parse it ?
for example, I want to extract the data of 2nd client and item_lists.
I have been using JSON.parse(json), but I have no idea how to get the value.
var content = JSON.parse(res);
console.log(content.client_infos.client[1].no);
it's not work.
var object = JSON.parse(variableOrStringLiteral);
finally, I find out the right way to get the value that like this
var obj = JSON.parse(content);
obj.client_infos[0].client.no;

loop inside an array throws Uncaught TypeError: Cannot read property '1' of undefined

I am trying to make this simple loot system to work but I keep getting this TypeError and I have tried everything I could think of.
Everything is explained in the code I added below. It was working yesterday but it seems like today is no longer working...
Here is the code in the JS file:
console.info("Working!");
var items;
//here I get the json
$.getJSON('js/items.json', function(data) {
return items = data;
});
//run the function cuz laziness to put it every time in the console
loot();
function loot() {
//these are the drops from the mob
const ids = [1, 2, 3, 4, 5, 6, 7];
//define a random number to see what loot it drops
let rand = Math.floor((Math.random() * 100) + 1);
var loot;
//if the chance is between 1 and 5(including them) do that
if (rand >= 1 && rand <= 5) {
var legends = [];
//here I loop inside the ids constant to see what items are legendary and if they are push them to the legends array
for (var id in ids) {
//HERE IS THE PROBLEM I get Uncaught TypeError here and I have tried everything
if (items[ids[id]].rarity == "Legendary") {
legends.push(ids[id]);
};
};
console.log(`legends: ${legends}`);
//then I random the items inside legends array to get the loot
loot = legends[Math.floor(Math.random() * legends.length)];
};
console.warn(`You looted a ${items[loot].name} | ${items[loot].rarity}`);
};
and here is the JSON file:
{
"1": {
"id": 1,
"name": "Sword of Heaven",
"rarity": "Legendary"
},
"2": {
"id": 2,
"name": "Wooden Sword",
"rarity": "Common"
},
"3": {
"id": 3,
"name": "Glass of the Gods",
"rarity": "Rare"
},
"4": {
"id": 4,
"name": "Minor HP Potion",
"rarity": "Common"
},
"5": {
"id": 5,
"name": "The Enchiridion!",
"rarity": "Legendary"
},
"6": {
"id": 6,
"name": "Major MP Potion",
"rarity": "Rare"
},
"7": {
"id": 7,
"name": "Helm of the Forsaken",
"rarity": "Rare"
}
}
try to move your loot function into asynchronous getJson's callback:
console.info("Working!");
var items;
//here I get the json
$.getJSON('js/items.json', function(data) {
items = data;
//run the function cuz laziness to put it every time in the console
loot();
});
if you run it outside of this callback, items variable is not populated yet
if you want to use as function, move AJAX call into loot function, store result and make sure to run it only once:
function lootRun(refresh) {
// use self in order to reach it from anonymous callback
var self = this;
if (!self.items || refresh) {
$.getJSON('js/items.json', function(data) {
// kind of inner functional cache
self.items = data;
loot(self.items);
});
}
else {
loot(self.items);
}
}
function loot(items) {
//these are the drops from the mob
const ids = [1, 2, 3, 4, 5, 6, 7];
//define a random number to see what loot it drops
let rand = Math.floor((Math.random() * 100) + 1);
var loot;
//if the chance is between 1 and 5(including them) do that
if (rand >= 1 && rand <= 5) {
var legends = [];
//here I loop inside the ids constant to see what items are legendary and if they are push them to the legends array
ids.forEach(function(id) {
//HERE IS THE PROBLEM I get Uncaught TypeError here and I have tried everything
if (items[id].rarity == "Legendary") {
legends.push(id);
};
});
console.log(`legends: ${legends}`);
//then I random the items inside legends array to get the loot
loot = legends[Math.floor(Math.random() * legends.length)];
console.warn(`You looted a ${items[loot].name} | ${items[loot].rarity}`);
};
};
now you can run your main loot function via lootRun, pass true to lootRun, if you want to refresh data from server
A few things to note - getJson is asynchronous, so items may be undefined. Move it into the getJson callback. Also, you're trying to get the name of an item that's undefined. You need to move the last console.log statement into the if statement so that you aren't using loot (which is undefined) to index the array.
var data = {
"1": {
"id": 1,
"name": "Sword of Heaven",
"rarity": "Legendary"
},
"2": {
"id": 2,
"name": "Wooden Sword",
"rarity": "Common"
},
"3": {
"id": 3,
"name": "Glass of the Gods",
"rarity": "Rare"
},
"4": {
"id": 4,
"name": "Minor HP Potion",
"rarity": "Common"
},
"5": {
"id": 5,
"name": "The Enchiridion!",
"rarity": "Legendary"
},
"6": {
"id": 6,
"name": "Major MP Potion",
"rarity": "Rare"
},
"7": {
"id": 7,
"name": "Helm of the Forsaken",
"rarity": "Rare"
}
};
// here I get the json
$.getJSON('js/items.json', function(data) {
loot(data);
});
function loot(items) {
//these are the drops from the mob
const ids = [1, 2, 3, 4, 5, 6, 7];
//define a random number to see what loot it drops
let rand = Math.floor((Math.random() * 100) + 1);
var loot;
//if the chance is between 1 and 5(including them) do that
if (rand >= 1 && rand <= 5) {
var legends = [];
//here I loop inside the ids constant to see what items are legendary and if they are push them to the legends array
ids.forEach(function(id) {
//HERE IS THE PROBLEM I get Uncaught TypeError here and I have tried everything
if (items[id].rarity == "Legendary") {
legends.push(id);
};
});
console.log(`legends: ${legends}`);
//then I random the items inside legends array to get the loot
loot = legends[Math.floor(Math.random() * legends.length)];
console.warn(`You looted a ${items[loot].name} | ${items[loot].rarity}`);
};
};

If two JavaScript arrays of objects share elements, is all non-shared memory garbage-collected when one array is no longer referenced?

When two arrays have an element which points to (references) the same object, and you change the object via one array, it changes in the other array, as I have proven to myself in the first snippet below.
My question is, if array a1 is referenced in other code, such as an event handler, and a2 is not referenced anywhere else and goes out of scope, then do all "major" browsers garbage-collect the memory used by the a2 array itself, including pointers to the objects, and the memory for the object created in the 2nd push in the snippet below. If so, then since a2 no longer has pointers to the objects in a1, then if a1 finally goes out of scope, then will all of it's associated memory, including all objects it points to, be reclaimed by the GC, assuming no other pointers, besides those associated with a1 and a2, reference those objects?
I know it seems academic for this simple example, but I am writing an algorithm (see 2nd snippet) to make a nested object from a flattened version of the same data in an array, and in doing so I use a temp array which has elements pointing to each object in the original array. I plan to call it an indefinite amount of times, and I want to make sure I'm not leaking memory. There will be many more elements in the array than what is in the snippet.
I also know that there are other SO questions which have strong similarities to this one, and the answers have been helpful, but I don't think that anyone has definitively answered each part.
var a1 = [{first: 1, second: 2}, {first: 4, second: 2}, {first: 3, second: 4}];
var a2 = [a1[2]];
a2.push(a1[1]);
a2.push({first: 5, second: 8});
console.log('a1 = ' + JSON.stringify(a1, null));
console.log('a2 = ' + JSON.stringify(a2, null));
a2[0].first = 7;
a2[1].second = 9;
console.log('a1 = ' + JSON.stringify(a1, null));
console.log('a2 = ' + JSON.stringify(a2, null));
var events = [
{
"id": 7,
"parentId": 4,
"name": "Sub7",
"expected": 400,
"actual": 100
},
{
"id": 2,
"parentId": 1,
"name": "Sub2",
"expected": 200,
"actual": 100
},
{
"id": 4,
"parentId": 1,
"name": "Sub4",
"expected": null,
"actual": 100
},
{
"id": 8,
"parentId": 1,
"name": "Sub8",
"expected": 250,
"actual": 100
},
{
"id": 1,
"parentId": null,
"name": "Main",
"expected": null,
"actual": 100
},
{
"id": 6,
"parentId": 4,
"name": "Sub6",
"expected": 300,
"actual": 100
}
];
var temp = [];
var parent;
for (var i = 0; i < events.length; i++) {
if (temp[events[i].id]) {
Object.assign(temp[events[i].id], events[i]);
} else {
temp[events[i].id] = events[i];
temp[events[i].id].children = [];
}
var parentId = events[i].parentId;
if (!parentId) {
parent = temp[events[i].id];
} else {
if (!temp[parentId]) {
temp[parentId] = {
id: parentId,
parentId: undefined,
name: undefined,
expected: undefined,
actual: undefined,
children: [temp[events[i].id]]
}
} else {
temp[parentId].children.push(temp[events[i].id]);
}
}
delete temp[events[i].id].parentId;
}
temp = undefined;
document.write('<code><pre>' + JSON.stringify(parent, null, 2) + '</pre></code>');
It's actually very simple. As soon as items are no longer reachable via code (something goes out of scope), it is marked for deletion. Whether it is garbage collected at that moment is a detail of the implementation, but it will no longer be available in code.
So, when array2 goes out of scope, it's data will go away, but if an element in array2 is used in array1, that single piece of data will not go away.
Here's more on that.
The short version is this: if no code can access it, it will be garbage collected.
You can imagine a graph that starts at the root node (think window) and each subsequent node is data which can be accessed from that node. In your case, you get something like this:
root --> event handler --> array1 ---
V
object
^
array2 ---
You can see that there is a path back to the root via array1. No such path exists for array2. Therefore, array2 will be cleaned up and any values which also do not have a link back to the root will be cleaned up as well.
object does have a path back to the root via array1. Therefore, array2s reference will be collected but the actual data which makes up object will not.

Javascript get value from array error

I need some help! Im retrieving some values from mySQL database using an external 'grabber'.
<?php
$datapiechart = file_get_contents("url which retrieves the values from MySQL");
?>
Which results in:
[{ "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }]
Then I want to select the values in this array.
<SCRIPT>
dataObjectdatapiechart = <?php echo $datapiechart; ?>
</SCRIPT>
<script> dataObjectdatapiechart.Name1</script>
I don't get whats going wrong here.
dataObjectdatapiechart is an array (with only one element), so you need to access it's contents using an indexer:
var item = dataObjectdatapiechart[0]; // Retrieve the object from the array
var name1 = item.Name1;
var name2 = item.Name2;
var name3 = item.Name3;
//etc.
Use
dataObjectdatapiechart[0].Name1
The Object { "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }
is at 0th position of the array.

Categories