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) );
Related
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:
Sort array of objects by string property value
(57 answers)
Closed 9 months ago.
I have an object that looks like the example below. I want the object that is equal to the id in the variable to be sorted first. How can I do that?
const id = 15;
const obje = [
{
"name": "Join",
"phone": "1234",
"email": "test#mysite.com",
"id": "12"
},
{
"name": "Join2",
"phone": "4321",
"email": "test2#mysite.com",
"id": "15"
}
]
What I want to do is to rank the object equal to the id in the variable to the top.
Thanks for your help in advance 🙏🏻
Instead of sorting find the index of the object where its id matches the search id, then splice it out, and then add it to the start of the array with unshift. You are mutating the array but it's quick, and without knowing the complete structure of your array, probably the easiest approach.
const id=15,arr=[{name:"Join",phone:"1234",email:"test#mysite.com",id:"12"},{name:"Join2",phone:"4321",email:"test2#mysite.com",id:"15"}];
const index = arr.findIndex(obj => obj.id === id);
arr.unshift(arr.splice(index, 1)[0]);
console.log(arr);
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);
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 8 years ago.
Problem: Create a javascript function that takes an object (of any size and depth), iterates through it and runs some basic string replacing on any strings and returns the object with the amended values.
I have two ideas about the implementaion, but cannot get a solution for either:
var context = {
"test1": "123",
"test2": "123",
"test2.2": "123",
"test3": {
"test4": "cats",
"test5": {
"test6": "test1",
"test123": "1231232"
}
}
};
Idea 1)
Loop the array, and change the values,
http://php.net/manual/en/language.references.pass.php
In some way similar to PHP
Idea 2)
Build an array of path(s) to the object, so to replace the "test123" value I can create such an array:
['test3', 'test5', 'test123']
... this part is simple, but how do I then convert this to something like:
context['test3']['test5']['test123'] ?
Thankyou in advance.
Loop over the object and invoke the function recursively if the value at hand is an object. In pseudocode:
function replaceInObject ( obj, find, repl)
for key in obj
value = obj[key]
if value is object
obj[key] = replaceInObject(value, find, repl)
else
obj[key] = value.replace(find, repl)
return obj
This question already has answers here:
Sort JavaScript object by key
(37 answers)
Sorting object property by values
(44 answers)
Closed 9 years ago.
I have an object that looks like:
{
"2013": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
},
"2012": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
},
"2011": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
}
}
The problem I am facing is, it seems only in Google Chrome that when I loop over this object the objects loop backwards.
The expected result of looping over and displaying the object should list out things from 2013, 2012, 2011. Which happens in Firefox.. However no change in the method, same exact object in Chrome.. I will get 2011, 2012, 2013
So with this I need to obviously apply some level of sorting over this object before looping over it, seeing as Chrome wants to get the loop to read over it backwards. Problem I am facing with that is not entirely sure how to sort an object with JS
Instead of property/value pair implement this structure as an array of objects. Arrays you can sort by any property of objects it contains.
Because objects are unordered collections, it's up to you to enforce the ordering you want.
One way is to get an Array of the object properties, sort them, then iterate the Array.
Object.keys(data)
.sort(function(a, b) {
return +b - +a;
})
.forEach(function(key) {
var item = data[key];
});
This assumes that you wanted a simple descending order.
When you iterate over object properties, there is no guarantee on the order. You can add your objects to an array, and sort the array instead:
var obj = {"2012" : {}, "2011" : {}, "2013" : {}};
var arr = [];
for (var year in obj) {
arr.push({year : year, data : obj[year]});
}
arr.sort(function(a,b) {
return b.year - a.year;
});
http://jsfiddle.net/wK5KE/
One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys:
Getting JavaScript object key list
Then you could use the javascript sort function:
http://www.w3schools.com/jsref/jsref_sort.asp
Or write your own if you feel inclined.
Then just loop through the array of keys, using object[key] to extract the value.