I have a list of different objects like this:
Object: { "march 2019": 21, "april 2019": 23, "may 2019": 121, etc... }
How can I set up individual objects from this previous list in javascript or jQuery?
Object: { "march 2019": 21 }
Object: { "april 2019": 23 }
Object: { "may 2019": 121 }
Thank you for your help
You could do with Object.entries and Array#map
updated with 3 different answer
const obj = { "march 2019": 21, "april 2019": 23, "may 2019": 121};
let res = Object.entries(obj).map((a,b)=>({[a[0]]:a[1]}));
//array object
console.log(res)
//single object
console.log(Object.assign({},...res))
//object object
console.log(res.reduce((a,b,c)=>(a[c]=b,a),{}))
You can either store the object in array or you can directly use inside the loop :
const obj = { "march 2019": 21, "april 2019": 23, "may 2019": 121};
Object.entries(obj).forEach(ob=>console.log({[ob[0]]:ob[1]}))
Hopefully it should work
You can try the following, this will give a single object:
let input_dict = { "march 2019": 21, "april 2019": 23, "may 2019": 121};
let output_dict = {};
Object.keys(input_dict).map(function (item) {
!output_dict.hasOwnProperty(item)?output_dict[item] = input_dict[item]:'';
});
console.log(output_dict)
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.
In my React Native application, I am accessing data from my store in the following form:
Array [
Checkout {
"date": 2020-12-27T13:24:08.734Z,
"id": "Sun Dec 27 2020 08:24:08 GMT-0500 (EST)",
"items": Array [
Object {
"productBrand": "Microsoft",
"productCategory": "Gaming",
"productId": "p1",
"productTitle": "Xbox",
"quantity": 2,
"x": 1.815,
},
Object {
"productBrand": "Apple",
"productCategory": "Computers",
"productId": "p2",
"productTitle": "MacBook Pro",
"quantity": 1,
"x": 1.905,
},
],
"total": 3.720,
},
Checkout {
"date": 2020-12-27T13:24:47.790Z,
"id": "Sun Dec 27 2020 08:24:47 GMT-0500 (EST)",
"items": Array [
Object {
"productBrand": "Apple",
"productCategory": "Computers",
"productId": "p2",
"productTitle": "MacBook Pro",
"quantity": 1,
"x": 1.905,
},
],
"total": 1.905,
},
]
I am trying to use VictoryPie to create a pie chart that shows productBrand weighted by the sum of x over all the objects. In this example, I would need a pie chart showing Microsoft and Apple, weighted by 1.815 and 2*1.905 = 3.81, respectively. Is there any way to do this without writing a separate function to calculate these sums? I would like the pie chart to update automatically every time new data is added to the store.
I tried this, where history is a variable containing the above array but no pie chart is produced.
<VictoryPie data={history} x={(data) => data.items.productBrand} y={(data) => data.items.x} />
See my working sample: https://codesandbox.io/s/react-victory-pie-chart-forked-kpe39?file=/src/index.js
Like this:
x="productBrand"
y={(data) => data.x * data.quantity}
For anyone trying to do something similar, I ended up extracting the data I needed by using a nested for loop within the useSelector hook:
const allBrands = useSelector(state => {
let allData = {};
for (const key1 in state.history.history) {
for (const key2 in state.history.history[key1].items) {
if (allData.hasOwnProperty(state.history.history[key1].items[key2].productBrand)) {
allData[state.history.history[key1].items[key2].productBrand] += state.history.history[key1].items[key2].x;
} else {
allData[state.history.history[key1].items[key2].productBrand] = state.history.history[key1].items[key2].x;
}
}
};
let dataArray = [];
for (const prop in allData) {
dataArray.push({ brand: prop, total: allData[prop] })
}
return dataArray
});
Passing allBrands to the VictoryPie data prop produced the correct pie chart.
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)
I recently got interested on using the spread operator syntax, so I tried some examples, I have this example of array:
var entities = [
{
"id": 1,
"age": 33,
"hobby": "games"
},
{
"id": 2,
"age": 28,
"hobby": "chess"
},
{
"id": 3,
"age": 21,
"hobby": "comics"
},
{
"age": 23,
"hobby": "games"
}
]
Then, to update all hobbies at "once" I do the following:
entities.forEach(function(entity, index) {
this[index] = {...entity, hobby: "Some String to update all hobbies"};
}, entities);
console.log(entities)
Which works but I was wondering if there's a more efficient or shorter way to achieve it while using the spread operator. Any suggestions?
EDIT:
forEach is not necessary for me, or even do it in that way, I was curious on whether the spread syntax could be used (or not) to update nested values
The spread operator doesn't really help when you're updating the list, like you do in your example. It's easier to just update the property of each object:
var entities = [ { "id": 1, "age": 33, "hobby": "games" }, { "id": 2, "age": 28, "hobby": "chess" }, { "id": 3, "age": 21, "hobby": "comics" }, { "age": 23, "hobby": "games" } ]
entities.forEach(entity => {
entity.hobby = "Some String to update all hobbies";
});
console.log(entities)
The spread operator is useful if you want to create copies of objects, like you might want to do in a .map:
var entities = [ { "id": 1, "age": 33, "hobby": "games" }, { "id": 2, "age": 28, "hobby": "chess" }, { "id": 3, "age": 21, "hobby": "comics" }, { "age": 23, "hobby": "games" } ]
const newEntities = entities.map(entity =>
({...entity, hobby: "Some String to update all hobbies"})
);
console.log(newEntities)
The spread operator will iterate over all keys in the object to copy them and their values into the new object. If you want more efficiency, don't use the spread operator. Just assign directly to each object as you iterate over the list:
entity.hobby = "Some String to update all hobbies"
Note that this modifies the object in the existing array. So you don't need to assign this[index]. Alternatively, you can use map() instead of foreach() to return a new array that is created from the existing array.
Not sure if spread operator is really needed for what you are doing?
You can also look into this link for some interesting usage of the spread, Array.from and rest operator.
More into just spread operator here.
If you are looking for a fancier/smaller way to write this, here's two, one that uses uses .map and spread to return a copy of entities, and another that uses .forEach and updates the same array entities:
const COMMON_HOBBY = 'Coding';
let entities = [{
"id": 1,
"age": 33,
"hobby": "games"
},
{
"id": 2,
"age": 28,
"hobby": "chess"
}];
// To assign to new array (copy)
let output = entities.map((entity) => ({...entity, hobby: COMMON_HOBBY }));
console.log(output);
// Mutate /edit same array entities
entities.forEach((entity) => entity.hobby = COMMON_HOBBY );
console.log(entities);
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} + ')');