Reputation: 127
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.
Upvotes: 2
Views: 248
Reputation: 4562
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);
Upvotes: 1
Reputation: 10627
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);
Upvotes: 1
Reputation: 847
Try using splice(startPosition, deleteCount).
In your scenario:
Object.keys(obj).splice(-1,1)
This should return a new array without the last element
Upvotes: 0