This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
I'm writing a js code that takes in a JSON of string arrays, that also has dates formatted as strings in it. Below is a sample code of the same.
var prods = [
{
"id": "56e535de-319f-4612-be83-3084a060b77e",
"createdDate": "2021-04-28T11:34:54.975",
"modifiedDate": "2021-04-28T11:34:54.976"
},
{
"id": "55753a5d-377d-4038-baf0-5ecbf620601a",
"createdDate": "2021-04-27T16:22:02.621",
"modifiedDate": "2021-04-27T16:22:02.621"
},
{
"id": "e9593d91-d884-40e8-8239-5f69794f2b3a",
"createdDate": "2021-04-27T15:29:55.737",
"modifiedDate": "2021-04-27T15:29:55.737"
}
];
prods = prods.map(function(a) {
a.createdDate = Date.parse(a.createdDate);
return a;
});
console.log(prods)
Here I'm able to convert for createdDate. I want to know how I can do for both createdDate as well as modifiedDate by looping over the JSON.
Thanks
something like that ?
const prods =
[ { id : '56e535de-319f-4612-be83-3084a060b77e'
, createdDate : '2021-04-28T11:34:54.975'
, modifiedDate : '2021-04-28T11:34:54.976'
}
, { id : '55753a5d-377d-4038-baf0-5ecbf620601a'
, createdDate : '2021-04-27T16:22:02.621'
, modifiedDate : '2021-04-27T16:22:02.621'
}
, { id : 'e9593d91-d884-40e8-8239-5f69794f2b3a'
, createdDate : '2021-04-27T15:29:55.737'
, modifiedDate : '2021-04-27T15:29:55.737'
}
]
prods.forEach((el,i,arr)=>
{
arr[i].createdDate = Date.parse(el.createdDate)
arr[i].modifiedDate = Date.parse(el.modifiedDate)
})
console.log(prods)
.as-console-wrapper {max-height: 100%!important;top:0;}
Related
This question already has answers here:
Group by array and add field and sub array in main array
(8 answers)
Closed 1 year ago.
As a newbie, I'm looking for the best approach to achieve the below:
Here is the Array I get from my DB query that contains a left join on the "class" table
[
{"legnumber":1,
"classcode" : "J"},
{"legnumber":1,
"classcode" : "Y"},
{"legnumber":2,
"classcode" : "J"}
]
And I would like to get something like this:
{
"legs": [
{
"legnumber" : 1,
"classes" : [
{"classcode" : "J"},
{"classcode" : "Y"}
]
},
{
"legnumber" : 2,
"classes" : [
{"classcode" : "J"}
]
}
]
}
Thanks a lot for your suggestions.
I'm using Sequelize in this project but I'm writing raw queries as I find it more convenient for my DB model.
Regards,
Nico
Hassan's answer is the more concise way to handle this, but here is a more verbose option to help understand what's happening:
const queryResults = [
{ legnumber: 1, classcode: 'J' },
{ legnumber: 1, classcode: 'Y' },
{ legnumber: 2, classcode: 'J' },
]
// create an object to store the transformed results
const transformedResults = {
legs: [],
}
// loop through each item in the queryResult array
for (const result of queryResults) {
// try to find an existing leg tha matches the current leg number
let leg = transformedResults.legs.find((leg) => leg.legnumber === result.legnumber)
// if it doesn't exist then create it and add it to the transformed results
if (!leg) {
leg = {
legnumber: result.legnumber,
classes: [],
}
transformedResults.legs.push(leg)
}
// push the classcode
leg.classes.push({ classcode: result.classcode })
}
console.log(transformedResults)
You can group your array items based on legnumber using array#reduce and then get all the values to create your result using Object.values().
const arr = [ {"legnumber":1, "classcode" : "J"}, {"legnumber":1, "classcode" : "Y"}, {"legnumber":2, "classcode" : "J"} ],
output = arr.reduce((r, {legnumber, classcode}) => {
r[legnumber] ??= {legnumber, classes: []};
r[legnumber].classes.push({classcode});
return r;
},{}),
result = {legs: Object.values(output)};
console.log(result);
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 years ago.
I'm trying to work with autocomplete from Materialize.
The API Request provides following data:
[
{
"id": 4007,
"name": "Curitiba, Paraná, BR"
},
{
"id": 4391,
"name": "Curitibanos, Santa Catarina, BR"
}
]
But I need format this data using JavaScript in something that looks like:
{
"Curitiba, Paraná, BR": null,
"Curitibanos, Santa Catarina, BR" , null
}
Thank you in advance for any help! :)
You can map your array of objects to an array of {[name]: null} objects. Here [name] is a computed property name, which allows you to use the value of the name variable as the key for your object. You can then merge the mapped array into one resulting object using Object.assign() along with the spread syntax (...).
See example below:
const arr= [ { "id": 4007, "name": "Curitiba, Paraná, BR" }, { "id": 4391, "name": "Curitibanos, Santa Catarina, BR" } ];
const res = Object.assign(...arr.map(({name}) => ({[name]: null})));
console.log(res);
All you have to do for this is to assign each name as a key in a new object:
const data = [
{
"id": 4007,
"name": "Curitiba, Paraná, BR"
},
{
"id": 4391,
"name": "Curitibanos, Santa Catarina, BR"
}
];
var object = {};
var i = 0;
for (i = 0; i < data.length; i++) {
object[data[i].name] = null;
};
console.log(object);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Loop through an array in JavaScript
(46 answers)
Closed 3 years ago.
I have the following data:
const temp = {
"_id" : "5def6486ff8d5a2b1e52fd5b",
"data" : {
"files" : [
{
"path" : "demo1.cpp",
"lines" : [
{
"line" : 18,
"count" : 0
}
]
},
{
"path" : "file2/demo2.cpp",
"lines" : [
{
"line" : 9,
"count" : 0
}
]
}
]
}
}
Now, I want to access the path, and line variable inside each of the files. I am still learning using JS and pretty new with Object.keys.
I have this:
Object.keys(temp.data.files).forEach(file => console.log(file));
This simply prints 0 and 1. Where am I going wrong in this?
This is because temp.data.files is an array. Object.keys is used to loop through Object.
Try this:
const temp = {
"_id": "5def6486ff8d5a2b1e52fd5b",
"data": {
"files": [
{
"path": "demo1.cpp",
"lines": [
{
"line": 18,
"count": 0
}
]
},
{
"path": "file2/demo2.cpp",
"lines": [
{
"line": 9,
"count": 0
}
]
}
]
}
}
temp.data.files.forEach(file => console.log("path ", file.path, " lines ", file.lines));
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 5 years ago.
I would like to combine topData and bottomData into completeData.
var topData = {
"auth": "1vmPoG22V3qqf43mPeMc",
"property" : "ATL-D406",
"status" : 1,
"user" : "test001#aaa.com",
"name" : "Abraham Denson"
}
var bottomData = {
"agent" : "pusher#agent.com",
"agency" : "Thai Tims Agency",
"agentCommission" : 1000,
"arrival" : "arrive 12pm at condo",
"departure" : "leaving room at 6pm",
}
var completeData = topData.concat(bottomData)
Since these are not arrays, concat wont work here.
Can this be done without making foreach loops?
You can use Object.assign() to concatenate your objects.
var newObj = Object.assign({}, topData, bottomData)
From MDN:
The Object.assign() method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
var topData = {
"auth": "1vmPoG22V3qqf43mPeMc",
"property" : "ATL-D406",
"status" : 1,
"user" : "test001#aaa.com",
"name" : "Abraham Denson"
}
var bottomData = {
"agent" : "pusher#agent.com",
"agency" : "Thai Tims Agency",
"agentCommission" : 1000,
"arrival" : "arrive 12pm at condo",
"departure" : "leaving room at 6pm",
}
var completeData = Object.assign({}, topData, bottomData);
console.log(completeData);
You can use Object.assign.
var topData = {
"auth": "1vmPoG22V3qqf43mPeMc",
"property": "ATL-D406",
"status": 1,
"user": "test001#aaa.com",
"name": "Abraham Denson"
}
var bottomData = {
"agent": "pusher#agent.com",
"agency": "Thai Tims Agency",
"agentCommission": 1000,
"arrival": "arrive 12pm at condo",
"departure": "leaving room at 6pm",
}
var completeData = Object.assign(topData, bottomData);
console.log(completeData)
It return the target object which mean properties from bottomData will be added to topData
var completeData = {...topData, ...bottomData};
This is object spread syntax.
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I need to traverse a JavaScript object with a stored string.
Sample string
var x = "Desserts"
Sample Object
{
"dataset":
{
"Categories" :
[
{
"Desserts" :
[
"Sweets","Ice Creams","Pastry"
]
} ,
{
"Juices and Beverages" :
[
"Cold","Hot","Fresh","Sodas"
]
}
}
}
If I traverse the object as dataset.Categories.x, it doesn't work[returns undefined] . How can I do this?
You should use dataset.Categories[0][x] instead of dataset.Categories[0].x
Take a look at : dot notation or the bracket notation
var x = "Desserts",
data = {
"dataset": {
"Categories": [{
"Desserts": ["Sweets", "Ice Creams", "Pastry"]
}, {
"Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
}]
}
}
alert(data.dataset.Categories[0][x]);
var obj = {
"dataset": {
"Categories": [{
"Desserts": ["Sweets", "Ice Creams", "Pastry"]
}, {
"Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
}]
}
}
var x = 'Desserts';
var val = obj.dataset.Categories[0][x];
console.log(val);
JSFIDDLE.