Parse Json array push javascript - javascript

I have Json Parse list which need to push each category list.
example :
listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
var values = [];
for(var i=0;i<listChartPeriods.length;i++){
categoryData.push(listChartPeriods.slice(0,1)[0]); //here need to push each date
values.push(listChartPeriods[i])
}
expected out put:
categoryData=["2018-05-04","2018-05-11","2018-05-18","2018-05-25","2018-06-01"]
values=[21807210.5028442,21807210.5028442,21807210.5028442]//each category values

Just use Object.keys to get the dates in the array.
const listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = Object.keys(listChartPeriods);
console.log(categoryData);

Below should get the job done for you. A for in loop is your friend when it comes to working with objects.
var listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
for(var char in listChartPeriods){
for(var i = 0; i < listChartPeriods[char].length; i++){
categoryData.push(listChartPeriods[char][i]);
}
}
console.log(categoryData);
EDIT: Just read your updated question and you are only wanting the key names. You can also do this with a for in loop.
for(var char in listChartPeriods){
categoryData.push(char)
}
console.log(categoryData);

Following the solution:
for (let date in listChartPeriods){
categoryData.push(date);
let [first] = listChartPeriods[date];
values.push(first);
}
categoryData = ["2018-05-04", "2018-05-11", "2018-05-18", "2018-05-25", "2018-06-01"]
values = [21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442]

Related

objects not properly pushed in array

The code below is supposed to decompose a json object sent from Postman into smaller objects that will be stored in a array. The problem is that if I console.log the result, I do see each and every objects decomposed as expected but the array.push method only push the last element of the inner array :
app.post('/commande',async(req,res)=>{
if( await authentification(req.query.login, req.query.pass)){
var data = req.body.data; // array containing json object to be posted
var dataLength = data.length;
var bigObj= []; //array to store objects
for (var i = 0; i<dataLength; i++) {
var orderLines = data[i].orderLines;//array of orders
var info ={};// object unit
info.CptClient = data[i].clientAccount;
info.customerOrderNumber= data[i].customerOrderNumber;
info.orderLabel = data[i].orderLabel;
var shipTo = data[i].shipTo;
info.recepientName = shipTo.recepientName;
info.contactName = shipTo.contactName;
info.ad1 = shipTo.ad1;
info.ad2 = shipTo.ad2;
info.ad3 = shipTo.ad3;
info.postalCode = shipTo.postalCode;
//"etc..."
//
for (var j = 0; j<orderLines.length;j++) {
info.itemRef = orderLines[j].itemRef;
info.itemQty = orderLines[j].itemQty;
info.unitPrice = orderLines[j].unitPrice;
console.log(info);//displays unique orderLabel : ABC01 ABC02 ABC03 XYZ01 XYZ02 XYZ03
bigObj.push(info); // stores only last of each type : ABC03 ABC03 ABC03 XYZ03 XYZ03 XYZ03
}
}
res.json(bigObj)
}else {
res.send("not authorized");
}
})
As explained in the comments, the console.log displays the right information as the objects are being created but the push method somehow would only push the last element of the orderLines array. Is there somebody to explain this phenomenon? Any idea? Thank you.

Not able to get object values

My array:
[
{
"date":"2018-04-01",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-02",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-03",
"time":[{"10:00":"12"},{"12:00":"25"}]
}
]
I need to get every date and time. To get this I am using a for loop. But not able to get date and time.
My script:
var slots = req.body.availableSlots;
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i]);
console.log(slots[i].date);
}
When getting date always says undefined.
It seems like req.body.availableSlots is coming as a multidimensional object array.
So full code need to be:-
var slots = req.body.availableSlots;
for(var i=0;i<count;i++){
var sub_array = slots[i];
for(j = 0; j<sub_array.length;j++){
console.log(sub_array[j].date);
}
}
Instead of using jquery library (jQuery.parseJSON()) use javascript inbuilt JSON.parse
var slots = '[{"date":"2018-04-01","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-02","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-03","time":[{"10:00":"12"},{"12:00":"25"}]}]';
slots = JSON.parse(slots);
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i].date);

For loop into array in a certain format

I've been trying to create an array from a for loop, using push which creates an array in the format ["value, value, value, value, value, value"] but I need it to create an array in the following format: [["value, value, value"],["value, value, value"]
The original array is created without a for loop like this:
new array (["1","2",3"],["1,2,3"],["1,2,3"],["1,2,3"]);
so how do I go about creating the same using a loop instead?
var colour = ["red","green","blue","orange"];
for (i=1; i<5; i++){
var name = $("#name"+i).val();
var can = $("#candidate"+i).val();
arrayOfData = new Array([can,name,colour[i]]);
}
Just push your arrayOfData itself to an array.
var array = [];
var colour = ["red","green","blue","orange"];
for (i=1; i<5; i++){
var name = $("#name"+i).val();
var can = $("#candidate"+i).val();
arrayOfData = [can,name,colour[i-1]];
array.push(arrayOfData);
}
​
Demo here: http://jsfiddle.net/f5J5z/4/

Can not parse JSON with JavaScript parser. Square brackets

I using JavaScript JSON library to parse JSON encoded array, received via POST.
Here is my code:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = JSON.parse(itemsRequest);
for(var i = 0; i<items.count(); i++)
{
var item = items[i];
alert(item.id);
}
I am not sure why, but the parser is just not liking that. How can I get it to parse?
Try items.length instead of items.count().
An array doesn't have a count method. Use the length property:
for (var i = 0; i < items.length; i++) {
Demo: http://jsfiddle.net/Guffa/Rt4db/
Below is the very good way to do:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = eval(itemsRequest); //Converted to actual JSON data
for (var item in items) {
alert(items[item]['id']);
}
Hope this is very helpful, thanks

How to "clean" an array in javascript?

I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']

Categories