Reputation: 6062
I have a JSON object, that is set dynamically. Below is the method onDragStop
that sets the columns:
data() {
return {
columns: [],
}
},
methods: {
onDragStop: function (index) {
this.$set(this.columns, index, {
xAxis: this.left,
position: ((this.left/SomeWidth) * 100),
});
}
}
Above will for example create a JSON object like below (for 2 columns):
[{"xAxis":329.2921875,"position":"30"},{"xAxis":658.584375,"position":"60"}]
Now, I need to pass this JSON object to a backend PHP file, that expects a layout like:
"{"1": {"position": "30"}, "2": {"position": "60"}}"
The PHP file simply encodes the JSON:
$columns = json_encode($request->columns);
Now I am trying to convert the JSON string to the desired output, by below method:
UpdateColumns: function (columns) {
this.columns = JSON.stringify(columns)
}
However above converts it like:
"{"columns":[{"xAxis":340,"position":"30.98"},{"xAxis":658.584375,"position":"60"}]}"
I was wondering, is it even possible to convert the JSON object to my desired output? And should this be done in the Vue file - or should I handle this on the backend PHP file?
Upvotes: 0
Views: 1624
Reputation: 4836
try this:
const data =[{"xAxis":329.2921875,"position":"30"},{"xAxis":658.584375,"position":"60"}];
const result = data.map(res=>({position: res.position}))
.reduce((map, obj, i) => (map[i] = obj, map), {})
console.log(result);
Upvotes: 2