Hello I'am new to programming and I stumble upon on grouping array data by date from two arrays.
here is my arrays:
header = [
{"2019-04-22": "Sun, Apr 22, 2019"},
{"2019-04-21": "Sat, Apr 21, 2019"},
]
body = [
{"2019-04-22": "doing customer support”},
{"2019-04-22": "reply to emails"},
{"2019-04-21": "send message to customers"},
]
How do I group the arrays into one array as example below
combinearray = {
"2019-04-22": [
"Sun, Apr 22, 2019",
"doing customer support",
"reply to emails",
],
"2019-04-21": [
"Sat, Apr 21, 2019",
"send message to customers",
],
}
Grouping two array data by date seems completely not easy for me I'm a beginner to javascript programming. I would appreciate any answers.
You can do that in following steps:
First use concat() to combine both arrays i.e header and body
Then use reduce() on that. And pass empty object as second argument(the initial value of accumulator).
In inside reduce() callback use Object.keys()[0] to get date.
Check if the date if date is not already key of accumulator set it to empty [].
Use push() to add the elements to the array.
Note: This will not remove reference to the real object in header and body.
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a)
return ac;
},{})
console.log(res)
However as mentioned in the comments there is no need to have object with keys. Just simple array of the values of that key are enough. For that push() a[key] instead of a.
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a[key])
return ac;
},{})
console.log(res)
You can use combine arrays then use reduce
used spread syntax to merge arrays
use reduce to build an object in desired format
Object.entries to get date and it's respective value
Check if the date is already present as key on object or not, if it's already present push the value to it else create a new key
let header = [{"2019-04-22": "Sun, Apr 22, 2019"},{"2019-04-21": "Sat, Apr 21, 2019"},]
let body = [{"2019-04-22": "doing customer support"},{"2019-04-22": "reply to emails"},{"2019-04-21": "send message to customers"},]
let final = [...header,...body].reduce((op,inp) => {
let [key,value] = Object.entries(inp)[0]
op[key] = op[key] || []
op[key].push(value)
return op
},{})
console.log(final)
Related
I try to delete information from a JSON but when i put the og JSON to a new variable and then delete some of the information from both
example:
fs = require('fs');
var name = 'Assets/signup.json';
var m = JSON.parse(fs.readFileSync(name).toString());
const originalJSON = m;
let newJSONFile = originalJSON;
console.log(originalJSON)
newJSONFile.members.splice(0, newJSONFile.members.length)
console.log(originalJSON)
so this code should from what i know that it will asign a new JSON and then delete the members from newJSONFile and keep the members in the originalJSON but when i console.log(originalJSON) it output the members to be empty and i dont understand why
What looks like is your newJSONFile and originalJSON are both the same.
The objects in JS, they refer to same location. Unlike primitives we cant make a copy simply by using =. You can read more about it here
We can create deep copies using spread and other ways const newJSONFile = {...originalJSON} but this will still not deep copy the nested objects.
I am not aware of the structure your JSON is so can't suggest best way to create a deep copy.
You can use clone functions from libraries like lodash
UPDATED:
Create a deep clone of your original JSON, instead of just creating a reference. Then you can delete from the clone, and retain the original:
/* YOUR JSON FILE */
const newJSON = {
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
/* LOG OG JSON FILE */
console.log(newJSON);
/* DEEP CLONE JSON FILE - MAKES A COPY */
let deepCloneJSON = JSON.parse(JSON.stringify(newJSON));
/* DELETE FROM THE COPY, NOT THE ORIGINAL */
delete deepCloneJSON.members[1];
console.log(deepCloneJSON);
/* CHECK THE ORIGNAL IS STILL INTACT */
console.log(newJSON);
https://jsfiddle.net/pixelmedia/7j18y5sp/12/
Old responses due to vague question:
Your question seems rather confusing, but if you are trying to delete from your JSON, then use the following.
Example: This will delete the second, and leave the first (0).
delete originalJSON[1];
Another example:
Initial is: 1, 2, 3
const originalJSON = [1, 2, 3];
delete originalJSON[1];
console.log(originalJSON);
Expected output: 1, 3
Now updated to demonstrate with the additional information provided by the OP:
const newJSON = {
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
delete newJSON.members[1];
console.log(newJSON);
Expected output: removed 'Tinyruthless'
JSFiddle: https://jsfiddle.net/pixelmedia/7j18y5sp/1/
so my json will look like this:
{
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
and i want to make it so that i can go through it and then delete one of the members and keep the rest in the same order
so i thought that i could just do
console.log(`deleteing person`)
fs = require('fs');
var name = 'Assets/signup.json';
var m = JSON.parse(fs.readFileSync(name).toString());
const originalJSON = m;
let newJSONFile = originalJSON;
console.log(originalJSON)
newJSONFile.members.splice(0, newJSONFile.members.length)
console.log(originalJSON)
for(m in originalJSON.members) {
console.log(`for loop runs`)
if(originalJSON.members[m]['name'] !== args[0]) {
let addMember = {
"name": originalJSON.members[m]['name'],
"instagram": originalJSON.members[m]['instagram'],
"signupDate": originalJSON.members[m]['signupDate']
}
newJSONFile.members.push(addMember)
console.log(newJSONFile)
}else {
}
}
and it just deletes it from both
Hi I used below script for this scenario.
const orgObj = { foo: "foo", bar: [1, 2, 3] }
var clonedObj = Object.assign({}, orgObj);
clonedObj.bar = Array.from(clonedObj.bar);
clonedObj.bar.push(4);
console.log(orgObj)
console.log(clonedObj)
It will make complete saperate copy of you object and OrgObj will remain unchanged.
I have array like this structure
["12 18:00", "15 17:30","16 12:00", "12 21:30", "9 10:30"...]
and it has unknown number of elements. I want get every hour:minute for selected element.
Example: if ele=="12" then get 18:00, 21:30. Maybe array has more "12 16:30","12 13:00" etc elements. Then also get 16:30, 13:00. All get elements 18:00, 21:30, 16:30, 13:00
Help me for this solution.
You can do this:
const array = ["12 18:00", "15 17:30","16 12:00", "12 21:30", "9 10:30"];
const getItems = number => {
return array.filter(item => item.split(" ")[0] === number.toString()).map(item => item.split(" ")[1])
}
console.log(getItems(12));
I have a javascript object that is coming from Source1 and I am unable to change its native structure or naming convention. I am using this data to feed into a 3rd party plugin to generate some chart data. This plugin however is using the key names as the identifiers on the chart and they are not descriptive or clear enough.
I am trying to run the object through a conversion function where it will change all of the key names to their defined equivalent.
Here is an example of what I am trying to do:
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
function convertNames(obj){
// Converted names
var map = [{
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}];
// Loop through the object and convert all key names to their equivalent
for(var prop in obj){
// Convert Here
}
return obj;
}
Desired Output:
[{
SubmissionIdentifier: "28935",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "No",
},
{
SubmissionIdentifier: "28936",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "Yes",
}]
https://jsfiddle.net/hbg4sfqh/7/
I'd combine the .map array method and a function to convert your key names to get the result you want. To convert the key names, you'll want to use bracket notation, so something like: newObj[keyMap[oldKey]] = oldObj[oldKey] should work.
Here's a simple implementation for your example:
const obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
}, {
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}];
const nameMap = {
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}
function renameKeys(obj, map) {
const newObj = {};
for (let key in obj) {
newObj[map[key]] = obj[key];
}
return newObj;
}
console.log(obj.map(item => renameKeys(item, nameMap)));
I'd also note that if you happen to be using the lodash library, you can also use it's _.mapKeys method to do this.
I'm gonna use .map() function to change the key names. The input data will remain unchanged. Hope this helps.
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
var output = obj.map(element => ({
SubmissionIdentifier: element.SubmissionID,
CreationDate: element.MetaCreatedDate,
ProgramName: element.Program,
Viewed: element.ViewedByInvestigator
}));
I have object like below.
{
"lastViewTime": "May 09, 2013 08:36:09 PM GMT",
"browser":
{
"Firefox": 200,
"Others": 800,
"Safari": 0,
"Chrome": 522,
"IE": 45
}
}
from this I want to generate like below(I need to pass this in this manner only to some plugin the [] are important)
var browserData = [
['Firefox', data.browser.Firefox],
['IE', data.browser.IE],
['Safari', data.browser.Safari],
['Others', data.browser.Others],
['Chrome', data.browser.Chrome]
];
Now I want to add this key value pairs to browserData only if data.browser.Firefox means those values are > 0.
for this I need to have a for loop . but i m not able to understand how I can make this kind of object. if I m making an array and pushing int to that key value pairs it is not giving me this kind of structure.
If some one can guide me in this it will be great.
var browserData = [];
for(var i in data.browser){
if(data.browser.hasOwnProperty(i) {
browserData.push([i, data.browser[i]]);
}
}
I have a variable that contains the following JSON string:
{
"0" : "Jun 20, 2012 03:02 PM",
"1" : "Jun 20, 2012 03:26 PM",
"2" : "Jun 21, 2012 01:12 PM",
"3" : "Jun 21, 2012 01:25 PM",
"4" : "Jun 21, 2012 02:42 PM",
"5" : "Jun 21, 2012 02:43 PM",
"6" : "NULL"
}
I wish to convert this JSON to an array in javascript such that
array[0] has "Jun 20, 2012 03:02 PM" array[1] has "Jun 20, 2012 03:26 PM" and so on.
You must parse your JSON string into a javascript object first.
JavaScript
var object = JSON.parse(JSONString);
To polyfill browsers without JSON support:
http://bestiejs.github.com/json3/
Then, convert that object to an array:
JavaScript
var arr = [];
for(var i in object) {
if(object.hasOwnProperty(i)) {
arr.push(object[i]);
}
}
jQuery
var arr = $.map(obj,function(value){ return value; });
Fiddle: http://jsfiddle.net/iambriansreed/MD3pF/
Note: Since the original poster did not mention jQuery it is worth mentioning that loading jQuery for only these instances isn't worthwhile, and you would be better off using the pure JavaScript if you aren't already using jQuery.
Alternatively, if you're targeting ES5 and above:
// myObject = { '0': 'a', '1': 'b' };
var myArray = Object.keys(myObject).map(function(key) { return myObject[key]; });
// myArray = [ 'a', 'b' ];
var currentVersion = {/literal} {$displayedVersion} {literal};
var jsonObj = eval('(' + {/literal}{$json}{literal} + ')');