I wrote some code where data is going into an array. At each index, I have another array that has an array with five data elements. What I want to do is to add data at the end of each nested array.
var allTimeStamps = [];
var allTimeStampsData = [];
$.getJSON( "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo", function( data ) {
const responseData = data;
for(let key in responseData["Time Series (Daily)"]){
allTimeStamps.push(key);
allTimeStamps.push(parseFloat((responseData["Time Series (Daily)"][key]["3. low"])));
allTimeStamps.push(parseFloat(responseData["Time Series (Daily)"][key]["1. open"]));
allTimeStamps.push(parseFloat(responseData["Time Series (Daily)"][key]["4. close"]));
allTimeStamps.push(parseFloat(responseData["Time Series (Daily)"][key]["2. high"]));
allTimeStampsData.push(allTimeStamps);
allTimeStamps=[];
}
console.log("seperatedData", allTimeStampsData);
});
I am trying something like this:
Old
allTimeStampsData[0].append("121");
New
allTimeStampsData[0].push("121");
I wrote append because of Python. I was actually trying to push, but this is not working.
I am expecting output like:
[ ["08-2-2018",98,12,98,78,121] ,......]
The best way to do something like this is with a simple .map over the entries of the "Time Series (Daily)" property, from which you can extract the date and the low/open/close/high:
fetch("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo")
.then(res => res.json())
.then(responseData => {
const daily = responseData["Time Series (Daily)"];
const keys = [
'3. low',
'1. open',
'4. close',
'2. high',
];
const allTimeStampsData = Object.entries(daily)
.map(([date, infoObj]) => (
[date, ...keys.map(key => infoObj[key])]
));
console.log(allTimeStampsData[0]);
console.log(allTimeStampsData);
});
I believe what you're looking for is the push method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Initialize your array
var my_arr = ['Volvo', 'Ford', 'Chevrolet'];
Then use the push method to add a new value to it.
my_arr.push('Mercedes');
Now my_arr = ['Volvo', 'Ford', 'Chevrolet', 'Mercedes'];
You should explicitly assign the field in your allTimeStampsData array:
allTimeStampsData[allTimeStampsData.length] = allTimeStamps;
Thereafter, allTimeStampsData[i].push("121"); will work.
I think the original question needs to be clarified here folks. As #josh mentioned that you use $.push() to append data to the end of an array. Regardless of how many levels deep the Array is using .push() is the best way to add data to an array. Also this sounds like a duplicate question which is posted here javascript-push-multidimensional-array
Related
Hi everyone I have object of object and I just want to combine data inside inner object in the form of array is there any way to that
input data
let data = {
ok123b:{
name:'shanu'
},
of123b:{
name:'rahul'
},
og1453jdfk:{
name:'ak'
},
ok1kjjdde23b:{
name:'man'
}
}
let arrayOfData =[data.ok123b.name,data.of123b.name,data.og1453jdfk.name,data.ok1kjjdde23b.name]
console.log(arrayOfData);
//this is hard coded i want dynamic code to convert data in the form of array
expected output
output = ['shanu','rahul','ak','man'];
There are several ways you can achieve this. I have updated my answer to include these.
Solution 1 (For loop and push() method)
You can use a simple for loop and push (add) each object's name to the array.
let data = {
ok123b:{name: 'shanu'},
of123b:{name: 'rahul'},
og1453jdfk:{name:'ak'},
ok1kjjdde23b:{name: 'man'}
}
let arrayOfData = [];
for(item in data) {
arrayOfData.push(data[item]['name'])
}
console.log(arrayOfData);
Solution 2 (Using Object.values() and map() method)
let data = {
ok123b:{name: 'shanu'},
of123b:{name: 'rahul'},
og1453jdfk:{name:'ak'},
ok1kjjdde23b:{name: 'man'}
}
let r = Object.values(data);
let result = r.map((element) => element.name)
console.log(result);
Solution 3 (One liner using Object.entries() and map() method)
let data = {
ok123b:{name: 'shanu'},
of123b:{name: 'rahul'},
og1453jdfk:{name:'ak'},
ok1kjjdde23b:{name: 'man'}
}
let result = Object.entries(data).map(a=>a[1].name)
console.log(result);
However as #Chris G mentioned, this is a very common question so you should probably browse similar questions such as:
Merge Objects
How can I merge properties of two JavaScript objects dynamically?
hi everyone if any one have same problem here is the solution
let data = {
ok123b:{
name:'shanu'
},
of123b:{
name:'rahul'
},
og1453jdfk:{
name:'ak'
},
ok1kjjdde23b:{
name:'man'
}
}
let r=Object.values(data);
let result =r.map((el) =>el.name)
console.log(result);
I'm trying to create a dataset from an API backend I've set up in my project. I've already managed to group my api call on the date but now I need to check the length of each date array that is created by lodash.
How would I do this because every attempt I've tried so far has failed. The image I've included shows the console.log after I have grouped my result, it also shows the amount of entries in each array which is exactly what I want to retrieve.
Current code, I removed my attempt at solving this problem because I would only get back undefined results.
ngOnInit() {
this._estimateService.getEstimates()
.subscribe(estimateData => {
const groupedEstimateData = groupBy(estimateData, 'estimate_date');
console.log(groupedEstimateData);
});
}
Example of desired result:
2019-12-09, 47
2019-12-10, 6
etc
Image:
I'm not sure of what you mean by "checking the length".
Here is an example of your desired console.log output
ngOnInit() {
this._estimateService.getEstimates()
.subscribe(estimateData => {
const groupedEstimateData = groupBy(estimateData, 'estimate_date');
Object.entries(groupedEstimatesData).map(([date, estimatedData]) => {
// do what you want there with each line
console.log(date, estimatedData.length);
});
});
}
You can have a look at Object.entries and map methods.
Good luck
You could do something like:
const groupsWithCounts = Object.keys(groupedEstimateData).map(key => {
[key]: groupedEstimateData[key],
total: groupedEstimateData[key].length
})
Now groupsWithCounts will be an array of objects with this structure:
{
2019-12-9: [item, item, item, ...], // the original items
total: 47 // the total count of items
}
You can do this simply with :
const dates = Object.keys(groupedEstimateData);
let output = {};
dates.forEach( date => output[date] = groupedEstimateData[date].length );
Object.keys(groupedEstimateData) will give you an array ["2019-12-09", "2019-12-10", etc]
You then iterate this array to construct this output object :
{
"2019-12-09" : 47,
"2019-12-10" : 6,
etc
}
My data is in the following format..
var data= [['typeName', 'valueName'], ['type1', 'value1'],
['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
I wish to transform the above data to data as below..
var resultdata=[{'typeName':'type1','valueName':['value1','value2']},
{'typeName':'type2','valueName':['value3','value4']}]
Basically I pick up distinct 'typeName' values and then group 'valueName' values by 'typeName' values.
I would preferably use only knockoutjs, lodash or underscorejs as my soln already uses them but I'm open to other solutions as well..
All help is sincerely appreciated
Thanks
I think this solution using underscore should do the trick:
var result= _.chain(data)
.rest()
.groupBy( value => value[0])
.map( (value,key) => ({ [data[0][0]]: key, [data[0][1]]: _.map(value, val => val[1])}))
.value();
This solution uses rest to skip the first item in the data array (the type descriptors). The array is then grouped by the first value in the array (the type) and the mapping returns the grouping in the required form using es6 object initializer notation.
Given the result as:
var resultdata=[
{'typeName':'type1'},{'valueName':['value1','value2']},
{'typeName':'type2'},{'valueName':['value3','value4']}
]
I'm going to call 'typeName' the category and 'valueName' the items.
Since the original data look like this:
var data= [
['typeName', 'valueName'],
['type1', 'value1'],
['type1', 'value2'],
['type2', 'value3'],
['type2', 'value4']
]
It is clear there is a pattern. The first row of data is what we'll use as labels for category and items. All the remaining data represent the values being used inside category and items.
The first step is to extract the labels:
var categoryLabel = data[0][0];
var itemLabel = data[0][1];
Next, the unique categories will need to be determined, so we'll use reduce to build an array of unique categories:
var categories = data
.filter(function(row, i) { return i > 0 }) // remove the labels
.reduce(function(arrCategories, currRow) {
// Add the current rows' category if it doesn't already exist
var currCategory = currRow[0];
if (arrCategories.indexOf(currCategory) === -1) {
return arrCategories.concat(currCategory);
}
return arrCategories;
}, [])
Now that you have a set of categories, you just need to iterate over each one to find all items that belong to it:
var valuesByCategory = {};
categories.forEach(function(category) {
// find all the data items that match the category
var items = data
.filter(function(row) { return row[0] === category; })
.reduce(function(arrItems, currRow) {
var currItem = currRow[1];
if (arrItems.indexOf(currItem) === -1) {
return arrItems.concat(currItem);
}
return arrItems;
}, []);
valuesByCategory[category] = items;
});
Now that all the data has been parsed out, the only thing left to do is build the resultant array:
var resultdata = [];
// iterate through each of the categories
categories.forEach(function(category) {
// using the category label, output an object with the label and category
var categoryObj = {};
categoryObj[categoryLabel] = category;
resultdata.push(categoryObj);
// Next, create a items object containing all the values
var itemsObj = {};
itemsObj[itemLabel] = valuesByCategory[category];
resultdata.push(itemsObj);
}
and that's it :)
The best part is that you don't need any external libraries. This is all ES2015 javascript!
Here is a lodash version of Gruff Bunnies solution:
var data= [['typeName', 'valueName'], ['type1', 'value1'], ['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
var names = data[0]
var values = _.tail(data)
console.log(JSON.stringify(
_(values)
.groupBy(0)
.map( (value, key) => ({ [names[0]]: key, [names[1]]: _.map(value, 1)}) )
.value()
))
https://jsfiddle.net/nmf1fdf5/
I have an array that stores the values:
var array = [['favorite color'],['black','red']]
to get black I would:
document.write(array[0][1][0]);
then if i append to the array another question [['favorite thing']['box','ball']]
If I wanted ball I would:
document.write.array[1][1][1];
I am having trouble understanding arrays. I want an array with one question and multiple answers then I want to loop through them and display everything. I can do the loop but I am unsure how to find things in nested arrays once I create them.
Use a combination of objects (which work like dictionaries) and arrays. For example:
var array = [
{'question' : 'favorite color', 'choices' : ['black','red'] },
{'question' : 'favorite thing', 'choices' : ['box','ball'] }
]
for( var i = 0; i < array.length; i++ ) {
var question = array[i]['question'];
var choices = array[i]['choices'];
// here you can display / write out the questions and choices
}
Bearing in mind, creating a class and using a constructor or init methods would probably be better to encapsulate the idea of questions and answers. But the above is the basic idea.
var array = [['favorite color'],['black','red','blue']];
document.writeln(array[1][1]);
document.write(array[1][2]);
Would print red then blue see it working live : http://jsfiddle.net/HJ872/
How?
array[0] => gets an *array* = ['favorite color']
=> array[0][0] gets this first element `favorite color`
array[1] => also gets this array = ['black','red','blue']
=> and then [1][1] will get 'red', [1][2] will get `blue`
I want to store objects in jquery. The objects are 'events' each event has a date, title and some text. They need to be stored like and array (maybe thats what they will be a multi-dimensional array) so I can iterate through them with a counter.
Edit,
I like the stores var as a way to group the info but how do I add multiple items and how do I index them?
var dates = new Array('12th Dec', '14th Jan', '6th May');
var event_title = new Array('My Birthday', 'Going to Beach', 'Holiday');
var event_text = new Array('One Year Older', 'Remember the suntan lotion', 'on the plane to spain');
I need to return by index alert(dates[2], event_title[2], event_text[2]);
you can try:
var store = {};
store = {
dates : dates,
titles: titles,
infotxt: infotxt
};
Then access:
store.dates or store.title or so..
You probably don't want to store separate related info in arrays as you're doing, and then attempt to access those groups by index.
JavaScript has a perfect, native object that allows you to group similar properties. Just use an object literal:
var events = [];
events.push({
data: someData,
title: someTitle,
text: someText
});
Now you have what's referred to oftentimes as a "collection".
You could take it a step further and make each event a "class":
function MyAwesomeEvent(data, title, text) {
this.data = data;
this.title = title;
this.text = text;
}
events.push(new MyAwesomeEvent(someData, someTitle, someText));
That approach is potentially heavy-handed depending on what your specific use-case is, but it's another option.