Reputation: 329
I am modifying a javascript object by altering a few things. When I recreate it, I get an index number for each key pair.
"0":{...},"1":{...},
How do I remove/omit the creation of these 0,1,2,3,4 numbers? so that the output just looks:
{...},{...},
var overlappedRanges = [{
start: '11/19/2019',
end: '11/20/2019'
}, {
start: '11/01/2019',
end: '11/18/2019'
}, {
start: '11/14/2019',
end: '11/19/2019'
}, {
start: '11/17/2019',
end: '11/21/2019'
}, {
start: '11/12/2019',
end: '11/23/2019'
}, {
start: '11/18/2019',
end: '11/24/2019'
}];
var final = {};
for (var key in overlappedRanges){
final[key] = {"startmod" : overlappedRanges[key]["start"],
"endmod" : overlappedRanges[key]["end"]};
}
console.log(JSON.stringify(final));
$('#overlapped').text(JSON.stringify(final));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="overlapped" style="color: red;"></span>
<br>
<span id="notOverlapped" style="color: green;"></span>
Upvotes: 0
Views: 48
Reputation: 191946
You are assigning the numeric indexes from the array as keys in the final
object. A simpler way to recreate the objects would be to use Array.map()
to iterate the array:
var overlappedRanges = [{"start":"11/19/2019","end":"11/20/2019"},{"start":"11/01/2019","end":"11/18/2019"},{"start":"11/14/2019","end":"11/19/2019"},{"start":"11/17/2019","end":"11/21/2019"},{"start":"11/12/2019","end":"11/23/2019"},{"start":"11/18/2019","end":"11/24/2019"}];
var final = overlappedRanges.map(({ start: startmod, end: endmod }) => ({
startmod, endmod
}));
console.log(JSON.stringify(final));
For browsers that don't support ES6, you'll need to replace the arrow function with a function that has a return statment, and create the object with standard assignment:
var overlappedRanges = [{"start":"11/19/2019","end":"11/20/2019"},{"start":"11/01/2019","end":"11/18/2019"},{"start":"11/14/2019","end":"11/19/2019"},{"start":"11/17/2019","end":"11/21/2019"},{"start":"11/12/2019","end":"11/23/2019"},{"start":"11/18/2019","end":"11/24/2019"}];
var final = overlappedRanges.map(function(o) {
return {
startmod: o.start,
endmod: o.end
}
});
console.log(JSON.stringify(final));
Upvotes: 1
Reputation: 370669
Have the outer structure be an array instead of an object:
var overlappedRanges = [{
start: '11/19/2019',
end: '11/20/2019'
}, {
start: '11/01/2019',
end: '11/18/2019'
}, {
start: '11/14/2019',
end: '11/19/2019'
}, {
start: '11/17/2019',
end: '11/21/2019'
}, {
start: '11/12/2019',
end: '11/23/2019'
}, {
start: '11/18/2019',
end: '11/24/2019'
}];
const final = overlappedRanges.map(({ start, end }) => ({
startmod: start,
endmod: end
}));
console.log(JSON.stringify(final));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="overlapped" style="color: red;"></span>
<br>
<span id="notOverlapped" style="color: green;"></span>
(Also, use .map
to transform one array into another)
Upvotes: 1