Changing of values of keys in JSON [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 months ago.
I have an application, where I use MongoDB, Express and MongoDB. On server side I received data by using find in such look - array of objects(JSON), which is named upProbations. For example, I find information about Max:
[
{
Name: 'Max',
DateOne: 2019-01-01T00:00:00.000Z,
DateTwo: 2019-04-01T00:00:00.000Z,
Info: 'Cheerful'
}
]
I want to change information a bit - fields DateOne and DateTwo. They have both types Date and I want to leave only 2019-01-01 and same for DateTwo, so i don't need time(hour, minute, second). The result should look like this:
[
{
Name: 'Peter',
DateOne: 2019-01-01,
DateTwo: 2019-04-01,
Info: 'Cheerful'
}
]
This result I will futher use for antoher calculations. I have tried such code, but it's not working:
upProbations = upProbations.map(function(a) {
a.DateOne = a.DateOne.toISOString().replace('T', ' ').substr(0, 10);
return a;
})
console.log(upProbations);
In which way I can do this?

let upProbations = [
{
Name: "Max",
DateOne: 2019-01-01T00:00:00.000Z,
DateTwo: 2019-04-01T00:00:00.000Z,
Info: "Cheerful",
},
];
upProbations = upProbations.map((eachObject) => {
const { DateOne, DateTwo, Name, Info } = eachObject;
return {
Name,
DateOne: DateOne.toString().split("T")[0],
DateTwo: DateTwo.toString().split("T")[0],
Info,
};
});
console.log(upProbations);

Related

Adding key value to inner array in a multidimensional array when key doesn't exist (javascript) [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I need to develop a function whereby a type property gets appended to an array if it doesn't exist.
So the key will be of type and it should have a value of "dog".
Can someone kindly point out how I can iterate over the array to check if the key "type" exists and also provide guidance on how to append {type:"dog"} to the inner array if it doesn't exist. I tried animalArray[0][1]={type:"dog"} but it doesnt seem to work.
A typical array of animals will look like this:
labelTheDogs(
[
{name: 'Obi'},
{name: 'Felix', type: 'cat'}
]
)
// should return [
{name: 'Obi', type: 'dog'},
{name: 'Felix', type: 'cat'}
]
This is not a nested array
function labelTheDogs(dogs) {
dogs.forEach(dog => {
if (!dog.type) {
dog.type = 'dog'
}
})
return dogs
}
const dogs = labelTheDogs(
[{
name: 'Obi'
},
{
name: 'Felix',
type: 'cat'
}
]
)
console.log(dogs)
you can use the map function to do that
const newArray = yourArray.map((element) => {
if(!element.type){
element.type = "dog";
}else {
return element
}
})

Map and sort data by date [duplicate]

This question already has answers here:
How to sort an object array by date property?
(25 answers)
How to sort an array of objects by date?
(4 answers)
Closed 12 months ago.
I retrieve an array of objects and I need to format it to make it acceptable for Google Charts. The initial data looks like so
[
{
"itemOne":111,
"itemTwo":1,
"itemThree":"2022-02-01T00:00:00.000Z"
},
{
"itemOne":222,
"itemTwo":2,
"itemThree":"2022-01-01T00:00:00.000Z"
},
{
"itemOne":333,
"itemTwo":3,
"itemThree":"2021-12-01T00:00:00.000Z"
},
]
To start the formatting, I do the following
const chartData = data.lastYear.map(
(item) => ([item.itemThree, item.itemTwo, item.itemOne]),
);
Which now leaves me with this.
[
["2022-02-01T00:00:00.000Z", 1, 111],
["2022-01-01T00:00:00.000Z", 2, 222],
["2021-12-01T00:00:00.000Z", 3, 333],
]
I have been trying however to sort the above by date. My current attempt is pretty bad, and obviously doesnt work.
const chartData = data.lastYear.map(
(item) => ([item.itemThree, item.itemTwo, item.itemOne]),
).sort((a, b) => {
return new Date(b.date) - new Date(a.date);
});
So what would be the best way to sort everything by date?
Thanks
let data = [
{
"itemOne":111,
"itemTwo":1,
"itemThree":"2022-02-01T00:00:00.000Z"
},
{
"itemOne":222,
"itemTwo":2,
"itemThree":"2022-01-01T00:00:00.000Z"
},
{
"itemOne":333,
"itemTwo":3,
"itemThree":"2021-12-01T00:00:00.000Z"
},
]
data.sort((a,b)=>{
return new Date(b.itemThree) - new Date(a.itemThree);
})
This sorts your data array according to date.
Hope this is helpful

Push an object into an array inside an object [duplicate]

This question already has answers here:
How can I get the full object in Node.js's console.log(), rather than '[Object]'?
(19 answers)
Closed 1 year ago.
First of all, I'm new in node js. I'm trying to create a REST API which looks like this:
[{
id: 1,
name: 'tushar hasan',
email: 'mtushar**#gmail.com',
devices: {
id: 2,
device_mac: '4A:34:ER:34:12',
relays: [
{
relay_name:"r1",
status:0
},
{
relay_name:"r2",
status:1
}
]
}
}]
But no matter what I'm trying it keeps on showing me below output:
[
{
id: 1,
name: 'tushar hasan',
email: 'mtushar**#gmail.com',
devices: {
id: 2,
device_mac: '4A:34:ER:34:12',
relays: [Array]
}
}
]
I'm providing you source code that's in below:
var x = [];
var data = {id :1, name:'tushar hasan', email:'mtushar**#gmail.com'};
var relay1 = {relay_name:'r1', status:0};
var relay2 = {relay_name:'r2', status:1};
var devices = {id:2, device_mac: '4A:34:ER:34:12'};
devices.relays = [];
devices.relays.push(relay1);
devices.relays.push(relay2);
data.devices = devices;
x.push(data);
console.log(JSON.stringify(x));
console.log(x);
By the way, when I call JSON.stringify(x), it provides me elements inside the relay array property. But without JSON.stringify(x) it doesn't show the elements inside relay property.
Thanks in advance.
Your code is fine. By default, when converting an object to string (like console.log does), the nested arrays will get converted to the text [Array]). The fact that you see the correct output when you call JSON.stringify asserts that it's really there.

Access part of an object javascript by id [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 1 year ago.
I have this object :
const list = {
id: 5,
name: "customer name",
projects: [
{
id:2,
title: "My project One",
studies: []
},
{
id:4,
title: "My project Two"
}
]
}
And I would like to be able to access a particular project in this object. There are only two of them here, but we imagine there could be more. How can I access a particular project by its ID? How can i do this ?
Thanks
You mention in the comments that the data is returned from an API. You can remap that data when it is received so that rather than a list of projects, it is an object keyed by the id field, which I assume is unique.
const allProjects = list.projects.reduce(
(collected, current) => {
return { ...collected, ...current };
}, {})
Failing that, you could use Array's filter to find the project you require:
const idToFind = 4;
const project = list.projects.filter( project => project.id === idToFind );

How to get array of same keys from an array of object in Javascript? [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
sorry before if this is an duplicate or have similarity with other post, but I cannot find problem with the same context as I have.
So I have an array of object, something like this
const queryResult = [
{ token: 'c5WKMXW8QdCFUg4q8ica' },
{ token: 'Othertoken' },
{ token: 'moreothertokens'},
]
So, i want to merge those 3 tokens into an array, something like this
['c5WKMXW8QdCFUg4q8ica', 'Othertoken', 'moreothertokens']
I am using forEach for the solution at the moment. But is there any shortcut or cleaner code?
Thank you.
Try this:
const tokens = queryResult.map(x => x.token);
If you have only one property in the objects, you could take a flat map approach with Object.values as callback.
const
queryResult = [{ token: 'c5WKMXW8QdCFUg4q8ica' }, { token: 'Othertoken' }, { token: 'moreothertokens'}],
tokens = queryResult.flatMap(Object.values);
console.log(tokens);
You could use map with object destructing
const queryResult = [
{ token: "c5WKMXW8QdCFUg4q8ica" },
{ token: "Othertoken" },
{ token: "moreothertokens" },
]
const tokens = queryResult.map(({ token }) => token)
console.log(tokens)

Categories

Resources