This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I'm trying to figure out how to access the value inside two dictionaries via JavaScript.
The JSON output from the server is;
{"meta":{},"linked":{custom_fields":[{"id":"4","name":"Department"}],"custom_field_values":[{"id":"0001","value":"Marketing","links":{"custom_field":{"id":"4","type":"custom_fields"}}}]
I need to list Marketing as the department. I can't seem to access "links" to pull the id.
If I create var linked = linked.custom_field_values; I get a response.
{"id":"0001","value":"Marketing","links":{"custom_field":{"id":"4","type":"custom_fields"}}}
As soon as I try to var cfl = linked.links.custom_field.id it's saying links isn't defined. So I'm not sure what I'm doing wrong in trying to create a variable for this?
Links is a dict with Custom_field right under as a dict with the values I need.
Wouldn't this print out the department correctly if everything works right?
if(cfl.id == 4){
console.log('Department is ' + linked.value);
}
It looks like custom_field_values an array. You have to look at the first item in the array like so var linked = linked.custom_field_values[0];
With a proper formatted object, you see, that you have an array inside. So you need to take an index for the array.
var object = {
meta: {},
linked: {
custom_fields: [
{
id: "4",
name: "Department"
}
],
custom_field_values: [
{
id: "0001",
value: "Marketing",
links: {
custom_field: {
id: "4",
type: "custom_fields"
}
}
}
]
}
};
console.log(object.linked.custom_fields[0].id);
console.log(object.linked.custom_field_values[0].id);
Related
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 months ago.
I would like to understand what am I doing wrong here. The problem is simple: I get an array in a response and I would need to access to its elements by name. Therefore I use Map to create a pair of Metric and Value. Subsequently, I use JSON stringify which I thought would be enough.
But when I try to access the element (array.Speed), I am getting Undefined.
var response=[
{
metric: "Speed",
value: "145",
},
{
metric: "Deceleration",
value: "76.5",
}
];
let array=[];
response.map(m=> {
array.push({
[m.metric]:m.value
});
});
var j=JSON.stringify(array);
console.log(j.Speed); //UNDEFINED
var js=JSON.parse(j);
console.log(js.Speed); //UNDEFINED
Stringify and access, converting to JSON later even, as described.
array is : [ { Speed: '145' }, { Deceleration: '76.5' } ] You can access speed like this: js[0].Speed .
The fact that j.Speed is undefined is to be expected since j is a string (and not an array neither an object)
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 months ago.
I am trying o get data from SWAPI to integrate with another platform using javascript. I have some saved some links inside a variable while getting data.
a = {
items: [
{ item: "https://swapi.dev/api/people/5/" },
{ item: "https://swapi.dev/api/people/68/" },
{ item: "https://swapi.dev/api/people/81/" },
],
};
From this code how do I extract the links only and save in a variable? I only need links. I tried object.values, object.keys() but couldn't find a way. The platform I am using doesn't support fetch() or $.each.
I am not quite sure how to get it done using for loop. Any assistance will be highly appreciated!
You can use a simple forEach for this task like:
const a = {
"items": [{
"item": "https://swapi.dev/api/people/5/"
}, {
"item": "https://swapi.dev/api/people/68/"
},
{
"item": "https://swapi.dev/api/people/81/"
}
]
};
a.items.forEach(el =>{
console.log(el.item);
});
Reference:
Array.prototype.forEach()
There are many different ways to achieve this, a few already suggested.
Using a for loop:
// Create an empty array to store the values
const linksArray = [];
// Loop the object items array to get its values
for (let i = 0; i < a.items.length; i++) {
// Store the values in the empty array
linksArray.push(a.items[i].item);
}
// See the results
console.log(linksArray)
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed last year.
I need a small Help in JS? i want to access mail_address of this nested object, how will I do it
const data =
{ members:
[ { id : '7d8c03e88a8386f6453340c1db56'
, mail_address : 'trial.om'
, uniqsl : 'c6cce01'
} ] }
const data = {
members: [
{
id: '7d8c03e88a8386f6453340c1db56',
mail_address: 'trial.om',
uniqsl: 'c6cce01',
}
]
}
console.log(data.members[0].mail_address) // Prints "trail.om"
members is a array of objects, but it has one single element. You access this element at the index 0.
This question already has answers here:
Javascript object literal - possible to add duplicate keys?
(3 answers)
Closed 1 year ago.
This is the scenario I am talking about:
let obj = {
id: "kjhgfr^&*()(*UY",
id: "kjhgfr^OIJHB",
id: "kjhgfr^)(*&^%Y",
id: "DFGHI(*&YTRDTYHKI*",
id: ")(IUHGVYUJKO))(*UY",
id: "VGYUKO(*UYH",
id: "BHYUIOP)(*&^T%",
id: "0987654567890",
id: "5678909876543",
};
I want to create an array with ids like this.
[
"5678909876543",
"0987654567890",
"VGYUKO(*UYH",
"kjhgfr^&*()(*UY",
"VGYUKO(*UYH",
];
Your object is incorrect.
Possible it is the same as:
Javascript object literal - possible to add duplicate keys?
As a result, it will be override to get the last value.
let obj ={id:"kjhgfr^&*()(*UY",id:"kjhgfr^OIJHB",id:"kjhgfr^)(*&^%Y",id:"DFGHI(*&YTRDTYHKI*",id:")(IUHGVYUJKO))(*UY",id:"VGYUKO(*UYH",id:"BHYUIOP)(*&^T%",id:"0987654567890",id:"5678909876543",};
console.log(obj);
// { "id": "5678909876543"}
You cannot have duplicate keys. Each identical key will overwrite the previously defined value.
You could try this instead (assuming you have control over the input):
let obj = {
id: ["kjhgfr^&*()(*UY",
"kjhgfr^OIJHB",
"kjhgfr^)(*&^%Y",
"DFGHI(*&YTRDTYHKI*",
")(IUHGVYUJKO))(*UY",
"VGYUKO(*UYH",
"BHYUIOP)(*&^T%",
"0987654567890",
"5678909876543"]
};
This is similar to the following question: Read and loop through an object with non-unique key value pairs
This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 4 years ago.
I have an array with multiple objects inside.
It's structured like that:
const Instructor = [
{ ID: '141',
InstructorNameAR: 'test',
InstructorNameEN: 'Mohamed Ahmed',
InstructorBriefAR: 'phd in chemistry',
InstructorBriefEN: 'phd in chemistry' },
{ ID: '140',
InstructorNameAR: 'test',
InstructorNameEN: 'Mahmoud Ahmed',
InstructorBriefAR: 'phd in chemistry',
InstructorBriefEN: 'phd in chemistry' },
]
I wanted to add other objects but filtered of duplicates based on their ID values.
Example of objects i want to add :-
const InstructorInstance = {
ID: 'ID',
InstructorNameAR: 'NAMEAR',
InstructorNameEN: 'NAMEEN',
InstructorBriefAR: 'BRIEFAR',
InstructorBriefEN : 'BRIEFEN'
}
I used this method to filter by ID.
But it didn't work as it compares only a single value of the array to the value i provided. which means it might be a duplicated object but still gets added because it did not check if it exists in each array element
Instructor.forEach(instance =>{
if(instance.ID !== InstructorInstance.ID){
Instructor.push(InstructorInstance);
}else{
console.log('Duplicate')
}
})
You have to loop the whole array first before deciding whether there is a duplicate or not. You can use forEach for that but every or some seem like the perfect fit for this kind of job:
const test = Instructor.every(instance => instance.ID !== InstructorInstance.ID);
if(test) {
Instructor.push(InstructorInstance);
}
Which means if every object in Instructor has a different ID than InstructorInstance, then push InstructorInstance into Instructor.
Note: You can put the test directly inside if without having to store it in a variable test:
if(Instructor.every(instance => instance.ID !== InstructorInstance.ID)) {
Instructor.push(InstructorInstance);
}
But that doesn't look, does it?
You can use some to check if that object already exists, if not, add it:
if (!Instructor.some(i => i.ID == instance.ID)) {
Instructor.push(instance);
}