Extracting values from a Javascript Object [duplicate] - javascript

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)

Related

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

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)

Why is array.push overriding the entire array? [duplicate]

This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I send a get request to the api wichh returns data under form of
{
"message": "<SUCCESS>",
"result": [
{
"i": 1,
},
{
"i": 2,
},
{
"i": 3,
} ]
}
Then in javascript (angular component.ts) I want to create an array ob objects but after pushing the objects in the array every array contains the data of the last object:
.subscribe(
data => {
type MyArrayType = Array<UserOpinion>;
let array: MyArrayType = [];
let cont: CustomInterface = {
i: ''
}
data.result.forEach(function(entry) {
cont.i = entry["i"];
array.push(cont);
console.log(cont);
//right value is shown
})
//console.log(array)
//array contains the connect number of objects but the objects are set on the same value: "i" = 3
Any ideas why this happens? Thank you
This should do it:
.subscribe(
data => {
type MyArrayType = Array<UserOpinion>;
let array: MyArrayType = [];
data.result.forEach(function(entry) {
array.push(entry);
});
}
);
You dont need cont just for copying the current object to another, you can use the current loop element directly.

Parsing JSON keys into array of strings [duplicate]

This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );

How to retrieve an specific value from a JSON involving multiple key value pairs using Javascript array [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I have following json
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
I can access for instance the second element of the array like this:
dictionary[1].value
it returns 10 which is the score of the History subject.
What I'm looking for is the way so that I can access it by the word "History" itself, I mean I need a code like this:
dictionary["History"].value
How can I achieve that?
Ok, so here is a hack. You can use Array as an Object and insert any key you want. You can apply forEach to it and bind keys with properties like below.
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
dictionary.forEach(function(item) {
dictionary[item.key] = item;
});
console.log(dictionary["History"].value);
Note: This is just a Hack and will fail in case of duplicate entries.
Edited
Solution in case of duplicate keys
var dictionary = [{
"key": "Math",
"value": "20"
}, {
"key": "History",
"value": "10"
}, {
"key": "Chemistry",
"value": "12"
}, {
"key": "Chemistry",
"value": "13"
}]
dictionary.forEach(function(item) {
if (dictionary[item.key] && !Array.isArray(dictionary[item.key])) {
dictionary[item.key] = [dictionary[item.key]];
dictionary[item.key].push(item);
} else if (dictionary[item.key] && Array.isArray(dictionary[item.key])) {
dictionary[item.key].push(item);
} else {
dictionary[item.key] = item;
}
});
console.log(dictionary["Chemistry"]);
By using find() to iterate over your array.
From MDN Array.prototype.find():
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
const dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
const result = dictionary.find(item => {
// if this returns `true` then the currently
// iterated item is the one found
return item.key === 'History'
})
console.log(result)
There's more than one way to do this but this one is the most straightforward and succinct.
Try this:
var dictionary = [
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
];
function getValue(searchKey) {
var retVal;
dictionary.some(item => {
if (item.key === searchKey) {
retVal = item.value;
return true;
}
});
return retVal;
}
console.log(getValue('History'));
If goes through your array of objects and finds the object that matches its key to your searchKey and returns the result.
Or you can convert your array of objects into a single object and then reference it directly:
var dictionary = {};
[
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
].forEach(item => {dictionary[item.key] = item.value;});
console.log(dictionary.History);

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

Categories