Cannot access a JSON attribute in a converted array [duplicate] - javascript

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)

Related

Extracting values from a Javascript Object [duplicate]

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)

How to access a dictionary inside a dictionary? [duplicate]

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

accessing specific part of JSON object with text string of keys [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
I have performed diff of two json files with the output being an array of strings indicating the location within a json tree.
The original json file is something along the lines of:
{
'key': {
'key3': 'value'
},
'key1': {
'key2': 'value2'
}
'key5': {
'key4': 'value4'
}
}
And the output of the diff is:
[
'key.key3',
'key1.key2'
]
I'm able to cycle through all the strings in the array:
(difference).forEach((k) => {
console.log(k);
})
How do I access the value from the original json file using the strings set by the forEach() function above? I want something like what would be returned if I called originalJSON.key1.key2 directly, but it has to be made up by the strings in the above function.
I've tried originalJSON[k] but that just returns undefined.
You have to split 'key.key3' into 'key' and 'key3'.
One way to do this is just to 'key.key3'.split(".") which gives ['key','key3']
Then you can use them to navigate through your original object :
(difference).forEach( k => {
var keys = k.split(".") // ['key','key3']
var val = originalJSON[keys[0]][keys[1]] // == originalJSON['key']['key3']
console.log(val); // 'value', 'value2', 'value4'
})

Angular2 Typescript how to retrieve an array from inside an object [duplicate]

This question already has answers here:
Find a value in an array of objects in Javascript [duplicate]
(20 answers)
Closed 5 years ago.
When I do console.log of the following:
console.log(this.categories);
I get this structure:
which was created from this json from the api:
[
{
"id":"dff0bb3e-889f-43e6-b955-52cc7203952f",
"name":"Wood",
"category_types":[
{
"id":"49b31f43-d98d-43c8-9798-088ec6914fe5",
"name":"Solid"
},
{
"id":"8592716a-ffd5-4e97-ba9e-6a64ba6e48f1",
"name":"Engineered"
}
]
},
{
"id":"6b2b6914-6c64-4389-a327-be3f08fd066d",
"name":"Carpet",
"category_types":[
{
"id":"0e2c8473-90fb-4806-a6e7-2389eeb0f9e4",
"name":"Loop pile"
},
{
"id":"3c762653-4f0d-42d2-a84e-133c7051c95b",
"name":"Cut pile"
},
{
"id":"0997d4dc-e886-46ef-83b4-d90c4fb72553",
"name":"Cut \u0026 loop pile"
}
]
}
]
Given that I have the value 'Wood' in a string variable called value, how do I get hold of the category_types array for the Wood object?
console.log(this.categories[value]);
returns undefined.
You want to find object that has name of 'Wood', then get category_types. Array.prototype.find returns first value that meets the condition in the provided test function. In your case, it could look like this:
this.categories.find(value => value.name === 'Wood').category_types
You can use Array.filter:
let wood = this.categories.filter(category => {
return category.name === "Wood";
})[0];
This will filter your categories to retrieve the ones with name wood, then you take the first one. If you didn't find anything with name === "Wood" in your array, then it will be undefined.

Parsing JSON in JavaScript using a variable [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
Was looking online for some help on this but couldn't find quite what I was looking for. I know how to parse a JavaScript variable, however, let's say I have the following JSON
{
"CPU INFO": {
"cpu0": "val",
"cpu1": "someval"
}
}
Let's assume I don't know how many CPUs there are and I want to set keys of a dictionary to the values. For example, if I had a loop such as:
for(var counterCPUS = 0; counterCPUS < numCPUs; counterCPUS++)
{
var currCPU = "cpu"+counterCPUS;
dictionary["cpu"+counterCPUS] = furtherCPUObject.currCPU;
}
Obviously this would not work since it would look for a String "currCPU", not "cpu0". How can I do what I am trying to achieve, assuming it is possible.
Thanks!
You can iterate objects using for..in, or you can get the object's keys as an array by using Object.keys and iterate over that:
var json = {
"CPU INFO": {
"cpu0": "val",
"cpu1": "someval"
}
};
for (var cpuKey in json['CPU INFO']) {
console.log(cpuKey, '=>', json['CPU INFO'][cpuKey]);
}
Object.keys(json['CPU INFO']).forEach(function(key) {
console.log(key, '=>', json['CPU INFO'][key]);
});

Categories