Trying to create a new object form a data model - javascript

I have a data model like this.
data: object = {
date: '11/11/18',
data: [3, 4, 7, 2, 5, 6, 8, 8]
}
The data array is from some inputs from the user. Starting from index 0, I would like them to be career, finances, personalGrowth, health, family, relationships, socialLife, attitude.
What im trying to do is get the lowest score (which would be 2 'health') and add it to an object like so.
data: object = {
lowestScore = 2,
lowerScoreName = 'Health'
}
Im fairly new to javaScript and im stuck on how to work this out.
Thanks

You could just make two related arrays (associative arrays) that look like this:
data: object = {
dataTypes: ['Career', 'Finances', 'Personal Growth', 'Health', 'Family', 'Relationships', 'Social Life', 'Attitude'],
dataValues: [3, 4, 7, 2, 5, 6, 8, 8],
}
Then obtain the lowest score:
lowestScore: Math.min(this.dataValues),
lowestScoreIndex: this.dataValues.indexOf(this.lowestScore);
And set the name of the lowest score:
lowestScoreName: this.dataTypes[lowestScoreIndex]
And there you go! Here's the full object:
data: object = {
dataTypes: ['Career', 'Finances', 'Personal Growth', 'Health', 'Family', 'Relationships', 'Social Life', 'Attitude'],
dataValues: [3, 4, 7, 2, 5, 6, 8, 8],
lowestScore: Math.min(this.dataValues),
lowestScoreIndex: this.dataValues.indexOf(this.lowestScore);
lowestScoreName: this.dataTypes[lowestScoreIndex]
}

Related

Create array of arrays from object properties in ReactJS

I have to create an array of arrays based on some object attributes.
So my object looks like this:
const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
}
Based on the userIds and dateIds I have to create an array of arrays with every attribute like this:
[[projectId, userId, dateId, task, duration, description]] <- this is what every number means
For every userId and dateId i have to create a new array.
And based on my example should be like this:
[[5, 2, 99, 'task', 8, 'description'],
[5, 3, 99 , 'task', 8, 'description'],
[5, 1, 99, 'task', 8, 'description'],
[5, 5, 99, 'task', 8, 'description'],
[5, 2, 100, 'task', 8, 'description'],
[5, 3, 100, 'task', 8, 'description']
... etc]]
Hope i explained my issue well. Thank you for your time!
My function:
const data = { projectId: 5, userIds: [2, 3, 1, 5], date: [99, 100, 101, 102], task: 'task', duration: 'duration', description: 'description' }
const parentArray = []
data.date.map(object =>
data.userIds.map(anotherObject => {
// console.log(anotherObject, object)
parentArray.push([data.projectId, object, anotherObject, data.task, data.duration, data.description])
}
))
console.log(parentArray)
const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
}
const result = data.userIds.map(uid => {
return data.dateIds.map(did => [data.projectId, uid, did, data.task, data.duration, data.description])
}).flat();
console.log(result);
Not exactly what you asked for but using your example you can create an array of objects which might add clarity by naming the properties (if some other user needs something like this). Note how I pass in the data and reference it with this and loop through the dateId's. Key is I never have to reference the original array, perhaps making this more maintainable internally;
const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
};
let x = [];
data.userIds.forEach(function(userid, index) {
this.dateIds.map((dateid, idx) => {
x.push({
project: this.projectId,
user: userid,
dateid: dateid,
tsk: this.task,
dur: this.duration,
desc: this.description
});
});
}, data);
x.forEach(function(el, index, array) {
console.log(el);
});

Looping through array of objects and storing it on a table[JS]

I am trying to loop through an array of objects and store it on the table, Here is the sequence of events my code is doing.
Grab values from a JSON file [done]
Store them in my code as array of objects like so[done]:
var results =
{name : [], goals: [], assists: [] , team: []};
3.Display the content in a table where I want the format to be below:
Name Goals Assists Team
Player 1 Name Player 1 Goals Player 1 Assists Player 1 Team
Picked up object containing arrays looks like so:
{
assists: [4, 2, 2, 9, 1, 7, 3, 6, 4, 6, 3, 1, 2, 7, 3, 1, 18, 3, 10, 9],
goals: [23, 20, 19, 19, 17, 16, 16, 16, 15, 15, 14, 13, 13, 12, 12, 11, 11, 11, 10, 10],
name: ['J. Vardy', 'P. Aubameyang', 'D. Ings', 'Mohamed Salah', 'R. Sterlin', 'S. Mané ', 'S. Agüero', , , , , , , , , , , ,],
team: ['Leicester', 'Arsenal', 'Southampton', 'Liverpool', 'Manchester City', 'Liverpool', 'Manchester City', , , , , , , , , , , ,],
}
My code sample obtain this is using the for each functionality as below but my results display nothing, Full code below: [in progress]
var stats, table;
var results =
{name : [], goals: [], assists: [] , team: []};
//We need to initiate a request to read the json file
$.getJSON('data/topscores.json')
.done(function(data){ // Once done do the below
$.each(data, function(keyIndex) { //Loop through the JSon, grab all values and store in obj array
results.name[keyIndex] = (data[keyIndex].player.name)
stats = data[keyIndex].statistics
results.goals[keyIndex] = (stats[0].goals.total)
results.assists[keyIndex] = (stats[0].goals.assists)
results.team[keyIndex] = (stats[0].team.name)
});
table = document.getElementById('rank').getElementsByTagName('tbody')[0] //Grabbing first contents of table body
for (var key in results.name.length) {
var row = document.createElement('tr'); //insert 20 rows beginning of the loop
Object.values(res).forEach(text => { //Loop through object array and store values in respective table cells
var cell = document.createElement('td')
var textNode = document.createTextNode(text)
cell.appendChild(textNode)
row.appendChild(cell)
});
table.appendChild(row)
}
}) //End of JSON function
Any help would be appreciated on how i can display the results array of objects into my table cells
If you have an element <table></table> and an object data containing your game data, you can display it in the table like so:
<!DOCTYPE html>
<html>
<body>
<table></table>
<script>
const data = {
assists: [4, 2, 2, 9, 1, 7, 3, 6, 4, 6, 3, 1, 2, 7, 3, 1, 18, 3, 10, 9],
goals: [23, 20, 19, 19, 17, 16, 16, 16, 15, 15, 14, 13, 13, 12, 12, 11, 11, 11, 10, 10],
name: ['J. Vardy', 'P. Aubameyang', 'D. Ings', 'Mohamed Salah', 'R. Sterlin', 'S. Mané ', 'S. Agüero', , , , , , , , , , , ,],
team: ['Leicester', 'Arsenal', 'Southampton', 'Liverpool', 'Manchester City', 'Liverpool', 'Manchester City', , , , , , , , , , , ,],
};
const titles = ['name', 'goals', 'assists', 'team'];
const createElement = document.createElement.bind(document);
const querySelector = document.querySelector.bind(document);
const table = querySelector('table');
const titleTr = createElement('tr');
table.append(titleTr);
titles.forEach(title => {
const th = createElement('th');
th.textContent = title.replace(/\w/, l => l.toUpperCase());
titleTr.append(th);
});
Object.keys(Object.values(data)[0]).forEach(i => {
const tr = createElement('tr');
titles.forEach(title => {
const td = createElement('td');
td.textContent = data[title][i];
tr.append(td);
});
table.append(tr);
});
</script>
</body>
</html>
The obcious issue I see is your iteration over json results. The for-in loop is for iterating over object's properties only and you want to iterate over an array results.name.
Even if you were iterating over an object, your for loop syntax doesn't make much sense (iterating over array's length?!).
Try it like this: for (let i=0; i<results.name.length; i++).
Also, what is res in Object.values(res)?!

Sum of array values at dictionary positions only - Javascript

I have x amounts of data sets to post into a line graph, and I want an additional line produced that is the sum of all dictionary entries at specific positions (in this instance, it's a date of entry). I only have 1 dictionary since the data is pulled prior from a database - dictionary called `all_users_experiences".
I'm trying to add the values together at each dictionary position and push into another array so i can then divide each position by the number of users to get the sum of each position, but for the life of me I can only find examples of regular arrays having positions appended, not dictionary values. New to JavaScript so any help would be wonderful!
arrays:
(2) [Array(30), Array(30)]
array contents (each number having a key is causing me the issue!):
(30) [1, 2, 5, 8, 9, 9, 4, 3, 3, 5, 6, 2, 2, 1, 5, 6, 7, 7, 7, 7, 6, 6, 4, 3, 4, 3, 2, 5, 7, 7]
(30) [5, 5, 6, 6, 7, 5, 5, 4, 3, 2, 1, 1, 6, 7, 8, 7, 7, 7, 6, 7, 8, 9, 7, 5, 6, 6, 7, 8, 7, 6]
I've successfully made this work with regular lists of number, but not dictionary values!
Thank you so much in advance.
EDIT:
Orignal unaltered Data was parsed into JS via python JSON can only show the pulled data from this file for sensitivity reasons. numbers in original question content is what is being collated with below.
Prior code tried (1 attempt of many...):
console.log(all_users_experiences) //Producing 2 arrays
console.log(all_users_experiences[0])
console.log(all_users_experiences[1])
var total_users = Object.keys(linegraph_data).length;
user_exp_aggregate = []
for (var i = 0; i < total_users.length; i++){
user_exp_aggregate.push(all_users_experiences[i][0] + all_users_experiences[i][1]);
console.log(user_exp_aggregate)
}
console.log("Total list: " + user_exp_aggregate)
EDIT2
Amended as per suggestion by Bergi but no data is being added to new array still :
user_exp_aggregate = []
console.log("Initial list: "+ user_exp_aggregate)
for (var i = 0; i < total_users.length; i++){
user_exp_aggregate.push(all_users_experiences[0][i] + all_users_experiences[1][i]);
console.log("updated list: " + user_exp_aggregate)
}
console.log("Total list: " + user_exp_aggregate)
Amended snapshot of result
example of how current data from arrays is being used in graph (trying to create a 3rd line graph data set showing the average between all users!):
enter image description here
This is probably what you are looking for:
all_users_experiences = [
[1, 2, 5, 8, 9, 9, 4, 3, 3, 5, 6, 2, 2, 1, 5, 6, 7, 7, 7, 7, 6, 6, 4, 3, 4, 3, 2, 5, 7, 7],
[5, 5, 6, 6, 7, 5, 5, 4, 3, 2, 1, 1, 6, 7, 8, 7, 7, 7, 6, 7, 8, 9, 7, 5, 6, 6, 7, 8, 7, 6]
]
user_exp_aggregate = []
//Loop to the full length for each
for (var i = 0; i < all_users_experiences[0].length; i++) {
user_exp_aggregate.push(all_users_experiences[0][i] + all_users_experiences[1][i]);
}
console.log("Total list: " + user_exp_aggregate)
//If you want to divide each value by total user count
user_exp_average = []
//var total_users = Object.keys(linegraph_data).length;
var total_users = 2 //Assuming total users are 2
for (var i = 0; i < user_exp_aggregate.length; i++) {
user_exp_average.push(user_exp_aggregate[i] / total_users);
}
console.log("Average: " + user_exp_average)
The issue happening in edit 2 part of code it that, the loop is only running till total user length. But as per your specification, you need to loop through all experiences to get the aggregate array and then divide each value by total number of users to get the average.
Hope it helps. Revert for any doubts.

Javascript .push causing array to nest deeper and deeper [duplicate]

This question already has answers here:
How to extend an existing JavaScript array with another array, without creating a new array
(20 answers)
Copy array items into another array
(19 answers)
Closed 3 years ago.
I'm sure this is an easy one, however my searches haven't helped as of yet.
When I push an array into another array, they nest a level deeper. The first array is at the correct depth.
var productArray = [{productID: currentProduct, productPrice: currentPrice, productName: productName, options: myOptions}];
if(localStorage.getItem("cart")){
var existingArray = JSON.parse(localStorage.getItem("cart"));
existingArray.push(productArray);
localStorage.setItem("cart", JSON.stringify(existingArray));
} else {
localStorage.setItem("cart", JSON.stringify(productArray));
}
Result:
0: Object { productID: "1", productPrice: "2.00", productName: "Chicken Sandwich", … }
​
1: 0: Object { productID: "1", productPrice: "2.00", productName: "Chicken Sandwich", … }
​
2: 0: Object { productID: "1", productPrice: "2.00", productName: "Chicken Sandwich", … }
You have multiple options to concatenate two arrays, but .push is not it (unless you iterate the 2nd array and push each element individually, OR followup with .flat())
let array = [1, 2, 3];
array.push([4, 5, 6]);
console.log(array); // [1, 2, 3, [4, 5, 6]]
array = array.concat([7, 8, 9]);
console.log(array); // [1, 2, 3, [4, 5, 6], 7, 8, 9]
array = [...array, ...[10, 11, 12]];
console.log(array); // [1, 2, 3, [4, 5, 6], 7, 8, 9, 10, 11, 12]
array.push(13, 14, 15);
array = array.flat();
console.log(array); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Because productArray is an array, and not an object, pushing it into another array will create another array, which will contain both, the initial array, and the new one.
To do what you were expecting, you should declare a new object, and push it into the existing array.
var productObject = {productID: 1, productPrice: 1, productName: '', options:{}};
var productArray = [];
if(localStorage.getItem("cart")){
var existingArray = JSON.parse(localStorage.getItem("cart"));
existingArray.push(productObject );
localStorage.setItem("cart", JSON.stringify(existingArray));
} else {
productArray.push(productObject);
localStorage.setItem("cart", JSON.stringify(productArray));
}
I think you are adding the entire "productArray" in the position n of your "existingArray". Try to make this.
var productArray = [{productID: currentProduct, productPrice: currentPrice, productName: productName, options: myOptions}];
if(localStorage.getItem("cart")){
var existingArray = JSON.parse(localStorage.getItem("cart"));
productArray.forEach(function(val){
existingArray.push(val);
})
localStorage.setItem("cart", JSON.stringify(existingArray));
} else {
localStorage.setItem("cart", JSON.stringify(productArray));
}

Iterate over multidimensional array, filter and create new one in javascript

I found this post but it's not really what I'm looking for. I have a huge JSON file with this structure:
{
foo: [1, 2, 3, ...],
bar: [
{
name: 'abc',
cl: 2,
data: [
[[2, 4, 6], [4, 5, 6]],
[[5, 3, 5], [5, 7, 9]],
[[6, 8, 9], [6, 8, 9]],
...
]
},
{
name: 'def',
cl: 1,
data: [10, 20, 30, ...]
}
]
}
I have a class representing the object and I can extract the properties and the objects inside the parent object. The foo property is mandatory while the bar property is optional. data is a numeric array that can be 1D or 3D. The foo.length and the data.length are always the same. I want to reduce the file size (in term of contents) but keeping the same structure, i.e. copy the old object to a new with exactly the same structure but shorter, so I could define a smaller length or range and get a new object, e.g. if I say to go from foo[0] to foo[1] then the data property will also go from data[0] to data[1] in the new object.
Is this possible? If yes, how can I achieve it? Maybe with map? but how?
function filter(obj, from, to){
/// ?
}
Regards.
EDIT:
The new reduced object should be something like this:
{
foo: [1, 2],
bar: [
{
name: 'abc',
cl: 2,
data: [
[[2, 4, 6], [4, 5, 6]],
[[5, 3, 5], [5, 7, 9]]
]
},
{
name: 'def',
cl: 1,
data: [10, 20]
}
]
}
You could use Array#slice for it.
function slice(obj, from, to) {
obj.foo = obj.foo.slice(from, to + 1);
obj.bar.forEach(function (a) {
a.data = a.data.slice(from, to + 1);
});
}
var object = { foo: [1, 2, 3], bar: [{ name: 'abc', cl: 2, data: [[[2, 4, 6], [4, 5, 6]], [[5, 3, 5], [5, 7, 9]], [[6, 8, 9], [6, 8, 9]], ] }, { name: 'def', cl: 1, data: [10, 20, 30] }] };
slice(object, 0, 1);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories