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

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.

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
}
})

Changing of values of keys in JSON [duplicate]

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);

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 );

Storing associative data by ID

I've got a lot of (user) objects which come from a socket. On every new connection I get a new user object, but on every disconnect I just got the ID of the recently disconnected user.
What's the best way to store these user objects client-side?
Already tried something like this (pseudo code without sockets and just for testing)
var connectedUsers = [];
connectedUsers[12] = {
id: 12,
name: "Test",
// ...
};
connectedUsers[29] = {
id: 29,
name: "Test 2"
};
Kinda works - but now I've got an array with lots of empty spaces. The upside is that it would be easy to remove a user just by his ID.
Using an object to store the objects probably won't be the right choice, since I don't have numeric indexes.
Use an object. The former indices are converted to strings and taken as properties for the object.
var connectedUsers = {};
Working example:
var connectedUsers = {};
connectedUsers[12] = { id: 12, name: "Test", };
connectedUsers[29] = { id: 29, name: "Test 2" };
document.write('<pre>' + JSON.stringify(connectedUsers, 0, 4) + '</pre>');

JavaScript Object property always returns undefined [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
Tell me what I am missing here. I have the follow javascript object.
[ { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD',
handle: '123',
userId: 'ABC123'} ]
When I do the following
success: function (registration) {
console.log(registration);
console.log(registration.handle);
Console log writes out the object as defined above. However when I do registration.handle I get an error saying "undefined." If registration is the above object why does registration.handle not work?
what am I missing?
You have an array containing an object. The properties you are trying to access are members of the object, not the array.
You must first get a reference to the object before you access its properties.
registration[0].handle
Try this
var registration=[ { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', handle: '123', userId: 'ABC123'} ]
alert(registration[0].handle)
DEMO
You are accessing the member of an object.
Do it like this way
success: function(registration) {
$.each(registration, function(index, data) {
var handle = data.handle;
console.log('id is getting now ' + handle);
});
}
Yes you first need to access array element then you can find object
console.log(registration[0].handle);
it is because you are having array so to access it try
registration[0].handle
EXAMPLE
CASE 1
registration = [ { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', handle: '123', userId: 'ABC123'} ];
console.log(registration[0].handle);
CASE 2
registration = { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', handle: '123', userId: 'ABC123'};
console.log(registration.handle);

Categories

Resources