I want to update array in object for each employeeID.
My "selected" array has the employeeID's to add.
The function adds the same time and jobs for all employees but after each iteration all the emplyeeIDs are the last employeeID that was pushed.
selected = [ "01PILGAR", "01DERREX", "01SANJAC" ]
updatePersonnelTime() {
console.log("updatePersonnelTime", this.time);
var newtime = this.time;
newtime.controlDateTime = new Date();
if(!this.currentJob.time){
this.currentJob.time = [];
}
for (let i=0; i < this.selected.length; i++){
newtime.employeeID = this.selected[i];
console.log('this.selected[i]: ', this.selected[i]);
this.currentJob.time.push(newtime);
console.log('this.time: ', this.currentJob);
}
this.updateJob();
this.timeRows = this.currentJob.time
},
This will add three time information to the array with all as the employeeID as "01SANJAC"
When I look at each push the employeeID shows each item from the array being pushed.
Why is the final array have all items with the last employeeID value?
final array =
[
{ "task": "1000", "inout": { "label": "In", "value": 1 }, "time": "08:00", "detailNotes": "time", "officeNotes": "office time", "controlDateTime": "2021-09-17T14:54:13.371Z", "employeeID": "01SANJAC" },
{ "task": "1000", "inout": { "label": "In", "value": 1 }, "time": "08:00", "detailNotes": "time", "officeNotes": "office time", "controlDateTime": "2021-09-17T14:54:13.371Z", "employeeID": "01SANJAC" },
{ "task": "1000", "inout": { "label": "In", "value": 1 }, "time": "08:00", "detailNotes": "time", "officeNotes": "office time", "controlDateTime": "2021-09-17T14:54:13.371Z", "employeeID": "01SANJAC" }
]
This is what solved it for me:
updatePersonnelTime() {
console.log("updatePersonnelTime", this.time);
var newtime = this.time;
newtime.controlDateTime = new Date();
if(!this.currentJob.time){
this.currentJob.time = [];
}
for (let i=0; i < this.selected.length; i++){
newtime.employeeID = this.selected[i];
console.log('this.selected[i]: ', this.selected[i]);
// added 'Object.assign in the push
this.currentJob.time.push(Object.assign({}, newtime));
console.log('this.time: ', this.currentJob);
}
this.updateJob();
this.timeRows = this.currentJob.time
},
In the .push i used "Object.assign({}, '')
This works for me.
updatePersonnelTime() {
console.log("updatePersonnelTime", this.time);
var newtime = this.time;
newtime.controlDateTime = new Date();
if(!this.currentJob.time){
this.currentJob.time = [];
}
for (let i=0; i < this.selected.length; i++){
newtime.employeeID = this.selected[i];
console.log('this.selected[i]: ', this.selected[i]);
// added 'Object.assign in the push
this.currentJob.time.push(Object.assign({}, newtime));
console.log('this.time: ', this.currentJob);
}
this.updateJob();
this.timeRows = this.currentJob.time
},
Related
I'm attempting to iterate through a JSON file, retrieving the calorie count for each item and then sorting by meal and day (in total, there are only five days of data). Here is an example of an object in the array.
"Date": "Thursday",
"Name": "Shredded Chicken",
"Icon": "Chicken",
"Type": "Dinner",
"Quantity": 85,
"Units": "Grams",
"Calories": 90
Currently, the totals for breakfastCalories, lunchCalories, dinnerCalories, and snackCalories are being added together (i.e. Monday's breakfastCalories is being added to Tuesday's breakfastCalories, and so on).
GOAL The intended result is to have an array for each day, listing the total breakfastCalories, et al. for that day. This only worked for day 1, print(calTotal[18]) returns [465,380,530,153,1528,899], which is the correct array of values for breakfastCalories, lunchCalories, dinnerCalories, snackCalories, grossCalories, netCalories.
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; //currently does nothing
let calTotal = [];
function setup() {
createCanvas(windowWidth, windowHeight);
loadJSON("finalJSON.json", cbSuccess, cbFail);
}
function draw() {
//to be utilized
}
function cbFail(data) {
print("Error loading JSON File");
print(data);
}
function cbSuccess(data) {
let myData = data; //load our JSON array
let calories = 0; //set a 0 starting value for calories
let breakfastCalories = 0;
let lunchCalories = 0;
let dinnerCalories = 0;
let snackCalories = 0;
let burnedCalories = 0;
for (let i = 0; i < myData.length; i++) { //count number of total entries in the dataset
if (myData[i].Type == "Breakfast") {
breakfastCalories += myData[i].Calories;
}
else if (myData[i].Type == "Lunch") {
lunchCalories += myData[i].Calories;
}
else if (myData[i].Type == "Dinner") {
dinnerCalories += myData[i].Calories;
}
else if (myData[i].Type == "Snacks") {
snackCalories += myData[i].Calories;
}
else if (myData[i].Type == "Exercise") {
burnedCalories += myData[i].Calories;
}
let grossCalories = round(breakfastCalories + lunchCalories + dinnerCalories + snackCalories);
let netCalories = round(breakfastCalories + lunchCalories + dinnerCalories + snackCalories - burnedCalories);
calTotal.push([round(breakfastCalories), round(lunchCalories), round(dinnerCalories), round(snackCalories), grossCalories, netCalories]);
}
}
More Concise Example (complete JSON data can be found here)
Example JSON
...
{
"Date": "Monday",
"Name": "Wild Pacific Sardines",
"Icon": "Fish",
"Type": "Lunch",
"Quantity": 85,
"Units": "Grams",
"Calories": 170
},
...
{
"Date": "Monday",
"Name": "Bacon, Sunday, Organic, Uncured",
"Icon": "Bacon",
"Type": "Dinner",
"Quantity": 1,
"Units": "Slice",
"Calories": 30
},
...
{
"Date": "Tuesday",
"Name": "Dressing, Vinaigrette, Lemon Pepper",
"Icon": "Oil",
"Type": "Lunch",
"Quantity": 2,
"Units": "Tablespoons",
"Calories": 200
},
For each day (Monday through Friday), add all values of Calories in Type == Breakfast together, all values ofCalories in Type == Lunch, etc, and at the end of the day, present calorie totals in an array.
You can use this code:
const data = fetch('https://api.npoint.io/0b9f68319d190f5d41ec')
.then(result => result.json())
.then((output) => {
return output;
}).catch(err => console.error(err));
data.then(items=>{
let result ={};
items.map(item=>{
let Date = item.Date;
let Type = item.Type;
if(result.hasOwnProperty(Date) && result[Date].hasOwnProperty(Type)){
result[Date][Type] += item.Calories;
}else if(result.hasOwnProperty(Date)){
result[Date][Type] = item.Calories;
}else{
result[Date]={};
result[Date][Type] = item.Calories;
}
if(Object.keys(result[Date]).length == 5){ //each day have 5 prop (Breakfast,Lunch,.)
result[Date]['netCalories'] = result[Date]['Breakfast']+result[Date]['Lunch']+result[Date]['Dinner']+result[Date]['Snacks'] - result[Date].Exercise;
result[Date]['grossCalories'] = result[Date]['Breakfast']+result[Date]['Lunch']+result[Date]['Dinner']+result[Date]['Snacks'];
}
});
console.log(result);
});
I have two array of objects, Based on one array I need to replace the key of another array. Tried to use Object.Keys() but could not achieve it. Kindly suggest
// **Input :**
let sim = {
"header": [{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
}
// **Reference Array:**
let columns = [{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
]
/// **Code I tried**
for (let i = 0; i < sim.header.length; i++) {
if (Object.keys(sim[i].header) === Object.keys(columns[i].header)) {
sim[i].header[columns[i].header.FIELD_DESC] = sim[i].header[Object.keys(sim[i].header)]
}
}
console.log(sim);
Expected Output:
output = {
"header": [{
"Sales Organization": "1000",
"Distribution Channel: "
10 "
},
{
"Sales Organization": "1000",
"Distribution Channel": "20"
}
]
}
Is not perfect but try this
let sim = {
"header": [
{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
};
let columns = [
{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
];
const filter = {};
for (let i = 0; i < columns.length; i++) {
filter[columns[i].FIELD] = columns[i].FIELD_DESC;
}
sim.header = sim.header.map(el => {
const keys = Object.keys(el);
const newObj = {}
for (const key of keys) {
newObj[filter[key]] = el[key];
}
return newObj;
});
console.log(sim);
Here is an approach using Map and array.map . We store the columns as key value pair in Map , then while traversing the sim.header , just get the value from the map for the particular key and update it .
let sim = {
"header": [{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
}
let columns = [{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
]
var map = new Map();
columns.forEach(obj => {
map.set(obj.FIELD, obj.FIELD_DESC);
})
sim.header = sim.header.map(obj => {
var tempObj = {};
Object.keys(obj).forEach(key => {
tempObj[map.get(key)] = obj[key]
})
return tempObj;
})
console.log(sim);
I am planning to filter an array into 2 separate arrays based on flag in one of the inner arrays but having trouble. Please help me with my code.
How do we get 2 separate arrays out of apiData to have objects filtered in types array based on flag value
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
},
"id": "1.2",
"flag": false
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
My Result should be like this for filteredTrueArray [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
I wanted $scope.filteredTrueArray to have types array with flag=true value objects and another array to have types array with only flag=false objects. Below is my code
$scope.filteredTrueArray = apiData.filter(function(item) {
var isTrueFound = item.types.some(function (el) {
return el.flag == true;
});
if(isTrueFound){
for(var i=0;i<item.types.length>0;i++)
{
if(item.types[i].flag == true){
$scope.filteredTrueArray.push(item.types[i]);
}
}
}
});
I've written a simple filter function. Please take a look!
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}, {
"id": "1.2",
"flag": false
}]
}, {
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}];
function filterByTypeFlag(records, flagValue) {
var filtered = [];
records.forEach(function (record) {
var matchedTypes = [];
record.types.forEach(function (type) {
if (type.flag === flagValue) {
matchedTypes.push(type);
}
});
if (matchedTypes.length) {
filtered.push({
"id": record.id,
"types": matchedTypes
});
}
});
return filtered;
}
filterByTypeFlag(apiData, true);
filterByTypeFlag(apiData, false);
Here is a sample code that creates an object with a boolean value and creates 2 arrays of objects bases off their boolean value. Sorry if I misunderstood what you were looking for.
var objArray = [];
class testObj {
constructor(Oname, test1) {
this.name = Oname;
this.isABoolean = test1;
objArray.push(this);
}
}
var test1 = new testObj("test1", false);
var test2 = new testObj("test2", true);
var test3 = new testObj("test3", false);
var test4 = new testObj("test4", true);
var test5 = new testObj("test5", false);
var objArray = [test1, test2, test3, test4, test5];
var trueArray = [];
var falseArray = [];
function createArrays() {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].isABoolean === true) {
trueArray.push(objArray[i]);
//console.log(trueArray[i].name);
} else if (objArray[i].isABoolean === false) {
falseArray.push(objArray[i]);
}
}
}
createArrays();
for (var j = 0; j < trueArray.length; j++) {
console.log("True value: " + trueArray[j].name);
}
for (var k = 0; k < falseArray.length; k++) {
console.log("False value " + falseArray[k].name);
}
EDIT: I cleaned it up to automatically add the objects to an array upon creation.
One solution is to use map() with a filter() for get the new types array.
var apiData = [
{
"id": 1,
"types": [
{"id": "1.1", "flag": true},
{"id": "1.2", "flag": false}
]
},
{
"id": 2,
"types": [
{"id": "2.1", "flag": true}
]
}
];
let filteredTrueArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => x.flag)})
)
.filter(({types}) => types.length);
let filteredFalseArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => !x.flag)})
)
.filter(({types}) => types.length);
console.log("FilteredTrueArray:", filteredTrueArray);
console.log("FilteredFalseArray:", filteredFalseArray);
I am trying to display tasks for each project using a Gantt chart. Unfortunately, I can only get the last project (with tasks) to show. It ignores other projects. I have included a link to the fiddle I am using for this example. What am I doing wrong here? This is my Javascript code:
var data = [
{
"project": "edo",
"tasks": [
{
"created_at": "2018-01-29 18:24:05",
"due_date": "2018-01-03 00:00:00",
"name": "new task"
},
{
"created_at": "2018-02-05 15:50:52",
"due_date": "2018-02-14 00:00:00",
"name": "new task1"
}
]
},
{
"project": "srgra",
"tasks": [
{
"created_at": "2018-02-05 15:51:29",
"due_date": "2018-02-16 00:00:00",
"name": "new textfield1"
},
{
"created_at": "2018-02-05 15:51:41",
"due_date": "2018-02-19 00:00:00",
"name": "new textfield2"
}
]
},
{
"project": "olotu project",
"tasks": [
{
"created_at": "2018-02-05 15:49:30",
"due_date": "2018-02-22 00:00:00",
"name": "new button"
},
{
"created_at": "2018-02-05 15:49:46",
"due_date": "2018-02-15 00:00:00",
"name": "new button2"
}
]
}
];
var today = new Date(),
day = 1000 * 60 * 60 * 24;
// Set to 00:00:00:000 today
today.setUTCHours(0);
today.setUTCMinutes(0);
today.setUTCSeconds(0);
today.setUTCMilliseconds(0);
today = today.getTime();
//console.log(data.length);
for(var i = 0; i < data.length; i++) {
var project = data[i].project;
var tasks = data[i].tasks;
//console.log(project);
var final = [];
for(var j=0; j < tasks.length; j++) {
final.push({
taskName: tasks[j].name,
start: today - 2 * day,
end: today + 14 * day
});
}
}
// THE CHART
Highcharts.ganttChart('analysis', {
title: {
text: 'Gantt Chart Test'
},
xAxis: {
currentDateIndicator: true,
min: today - 3 * day,
max: today + 18 * day
},
series: [{
name: project,
data: final
}]
});
Here is the fiddle I am following: https://jsfiddle.net/larsac07/t0r8qz9p/
Problem is where you define final variable. In your code, final variable is cleared (var final=[]) for every element in the data array:
for(var i = 0; i < data.length; i++) {
var project = data[i].project;
var tasks = data[i].tasks;
//console.log(project);
var final = []; // <---- this is wrong ---->
for(var j=0; j < tasks.length; j++) {
final.push({
taskName: tasks[j].name,
start: today - 2 * day,
end: today + 14 * day
});
}
}
It should be defined before the for-loop:
var final = []; // This will work
for(var i = 0; i < data.length; i++) {
var project = data[i].project;
var tasks = data[i].tasks;
//console.log(project);
for(var j=0; j < tasks.length; j++) {
final.push({
taskName: tasks[j].name,
start: today - 2 * day,
end: today + 14 * day
});
}
}
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 7 years ago.
Using jQuery I would like to compare 2 objects:
sourceArray:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
destination array
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
What I would like to do, is compare the target object with the source object based on the ID and find the mis-matched entries with a description on the resultant object. So the result will look like this:
var resultArray = [{
"Name": "Double",
"URL": "yyy",
"ID": 888,
"desc": "missing in source"
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345,
"desc": "missing in destination"
}];
Any quick help is really appreciated.
This isn't a good use of jQuery, but here is some vanilla javascript that does what you want.
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
https://jsfiddle.net/9gaxsLbz/1/
If you are wanting to dedupe your array, this will work:
var merged = origArray.concat(destArray);
var unique = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? false : this.push(item.ID);
}, []);
Fiddle: https://jsfiddle.net/Ljzor9c6/
If you are only wanting items that were duped, you can easily invert the condition:
var merged = origArray.concat(destArray);
var dupes = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? true : !this.push(item.ID);
}, []);
You can loop through the items in the first array and put the ID's in a map, then loop through the items in the second array and remove the matching ID's and add the missing.
Then just loop through the map to create the objects in the resulting array:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var map = {};
for (var i = 0; i < origArray.length; i++) {
map[origArray[i].ID] = 'source';
}
for (var i = 0; i < destArray.length; i++) {
var id = destArray[i].ID;
if (id in map) {
delete map[id];
} else {
map[id] = 'destination';
}
}
var resultArray = [];
for (key in map) {
var arr = map[key] == 'source' ? origArray : destArray;
for (var i = 0; arr[i].ID != key; i++) ;
resultArray.push({
Name: arr[i].Name,
URL: arr[i].URL,
ID: arr[i].ID,
desc: 'missing in ' + map[key]
});
}
// show result in StackOverflow snippet
document.write(JSON.stringify(resultArray));
var result = [];
for(var i = 0; i < oa.length; i++) {
var idx = mIndexOf(oa[i].ID);
if(idx > -1) {
oa.splice(i, 1);
da.splice(idx, 1);
}
}
for(var i = 0; i < oa.length; i++) {
var ln = result.length;
result[ln] = oa[i];
result[ln].desc = "missing in destination";
}
for(var i = 0; i < da.length; i++) {
var ln = result.length;
result[ln] = da[i];
result[ln].desc = "missing in origin";
}
function mIndexOf(id) {
for(var i = 0; i < oa.length; i++)
if(oa[i].ID == id)
return i;
return -1;
}
console.log(result);
0: Object
ID: 345
Name: "Double"
URL: "yyy"
desc: "missing in destination"
1: Object
ID: 888
Name: "Double"
URL: "yyy"
desc: "missing in origin"
jsfiddle DEMO
For things like this, you should use lodash. With lodash you can just do this:
var resultArray = _.defaults(destArray, origArray);