0

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?

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer... how about .reduce((map, obj, i) => (map[i+1] = obj, map), {}) to keep things the way OP wants them? Either way, this answer is good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.