how to replace ObjectId in JavaScript with Epoch Time
Ad
How do I iterate through a JSON string and replace every ObjectId into Unix Epoch time for further processing?
What I know: You get the first 8 chars from an objectId with:
subStrObjectId = objectId.substring(0, 8);
5668d142a54cc4960b55ea19 --> 5668D142
and convert these from hexadecimal into an Int value (epoch time in milliseconds):
subStrObjectIdInDec = parseInt(subStrObjectId, 16);
5668D142 (hex) --> 1449709890 (dec)
my Json string:
myJsonString = [
[
{"_id":"5668d142a54cc4960b55ea19","cid":10851045,"temp":25.4},
{"_id":"5668d14ea54cc4960b55ea1a","cid":10850909,"temp":24.9}
],
[
{"_id":"5668d14fa54cc4960b55ea1b","cid":10851045,"hum":37.9},
{"_id":"5668d3108c8cda92074b7ec9","cid":10850909,"hum":39.6}
],
[
{"_id":"5668d3198c8cda92074b7ecb","cid":10851045,"lux":34},
{"_id":"5668d31e8c8cda92074b7ecc","cid":10850909,"lux":68}
]
];
Ad
Answer
Ad
If you write what you know as a function:
function convert(id) {
return parseInt(id.substring(0, 8), 16);
}
You can easily iterate over your objects and run your function on the objects.
I'd prefer functional-style javascript:
var data = myJsonString.map(function (array) {
return array.map(function (item) {
item.time = convert(item._id);
return item;
})
})
console.log(data);
But you can go iterative with loops as well:
for (var i=0;i<myJsonString.length;i++) {
for (var j=0;j<myJsonString[i].length;j++) {
myJsonString[i][j].time = convert(myJsonString[i][j]._id);
}
}
console.log(myJsonString);
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad