Access part of an object javascript by id [duplicate] - javascript

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

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

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.

how to get an object inside an array with a value [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 1 year ago.
Array looks list :
[
{
"Name":"S",
"Level":"1",
"Uid":"huybd776",
"isHuman":false
},
{
"Name":"R",
"Level":"35",
"Uid":"673bjhbjhdcsy",
"isHuman":true
}
]
I have a value i.e Uid 673bjhbjhdcsy, how do I check if that Uid exists in the array and get the whole object associated with the Uid.
You can use find like:
const data = [
{
"Name":"S",
"Level":"1",
"Uid":"huybd776",
"isHuman":false
},
{
"Name":"R",
"Level":"35",
"Uid":"673bjhbjhdcsy",
"isHuman":true
}
];
console.log(data.find(x => x.Uid === '673bjhbjhdcsy'));
Reference:
Array.prototype.find()
result = [
{
"Name":"S",
"Level":"1",
"Uid":"huybd776",
"isHuman":false
},
{
"Name":"R",
"Level":"35",
"Uid":"673bjhbjhdcsy",
"isHuman":true
}
].find(item => item.Uid === '673bjhbjhdcsy')

Get value from object in array: js [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
This is what my array looks like:
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
And I have the uuid key in the variable:
const uuid = '111-111-111';
Now based on this uuid, I would like to extract the value from the amountMoney: 44.04.
How do you write this in a nice way in js?
You can use Array.prototype.find:
items.find(item => item.uuid === uuid) // -> found object
Use Array.prototype.find to find the object if the property uuid of the object matches the value of the variable uuid. Before extracting the value for amountMoney check if the object was found.
Example,
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
const uuid = '111-111-111';
const foundItem = items.find(item => item.uuid === uuid);
if (foundItem) {
console.log(foundItem.amountMoney)
}

Categories

Resources