I have an API from the stock market that returns a JSON object with sub objects the following way
Data: {
10:30: {
"high": 100
"low": 80
}
10:35: {
"high": 100
"low": 80
}
10:50: {
"high": 100
"low": 80
}
}
My plan is to get the data from the first object (e.g. 10:30), put it at the end of an array, and pass the array to a react-graph.js.
I have tried to copy the first object then delete it from the JSON array of objects but thought Object.keys(obj).pop() return the last object it doesn't delete it. This means the next iteration will return the same object and the same data.
I have also tried to get the last object from the array but I have searched for a function that return the last or first object but I did not find any.
-
You could splice out the last element of the array. splice(startPosition, deleteCount)Jorge Guerreiro– Jorge Guerreiro2021年01月19日 00:28:41 +00:00Commented Jan 19, 2021 at 0:28
-
It does not delete the object. I logged before and after splice, pop, unshift and the objects remain the same.Oslier– Oslier2021年01月19日 00:33:33 +00:00Commented Jan 19, 2021 at 0:33
-
1Splice will return a new array without the last elementJorge Guerreiro– Jorge Guerreiro2021年01月19日 00:35:56 +00:00Commented Jan 19, 2021 at 0:35
3 Answers 3
Object.keys(ObjectHere) returns a new Array with the keys. Acting upon that Array does not affect your Data Object... but that's not what you want to do anyways. You want to do like:
const data = {
"10:30": {
"high": 100,
"low": 80
},
"10:35": {
"high": 100,
"low": 80
},
"10:50": {
"high": 100,
"low": 80
}
}
function hiLow(hhmm){
return {[hhmm]: data[hhmm]};
}
const output = [];
output.push(hiLow('10:30'));
console.log(output);
Comments
You can use Object.entries() to get an array of key/value pairs, then you can shift() (removes first element and assigns to a variable) and create a new object from the entries:
let data = {
'10:30': {
"high": 100,
"low": 80
},
'10:35': {
"high": 100,
"low": 80
},
'10:50': {
"high": 100,
"low": 80
}
};
let entries = Object.entries(data);
let firstProp = entries.shift();
console.log(firstProp);
let newData = Object.fromEntries(entries);
console.log(newData);
1 Comment
Object.entries() should return the keys / values in definition order. Guarantees about object property ordering have changed in the last couple of yearsTry using splice(startPosition, deleteCount).
In your scenario:
Object.keys(obj).splice(-1,1)
This should return a new array without the last element