What's new

PHP Question for bot

jay41

Forum Veteran
Joined
Nov 13, 2016
Posts
1,927
Reaction
472
Points
658
Age
24
Help me to convert this code 1:One,2:Two into

var data = {
'One': '1',
'Two': '2',
};
using jquery
 
Sure! Here's how you can convert the code 1:One,2:Two into a JavaScript object using jQuery:

JavaScript:
var str = '1:One,2:Two';

// Split the string by commas to get individual key-value pairs
var pairs = str.split(',');

// Create an empty object to store the converted data
var data = {};

// Loop through each key-value pair
$.each(pairs, function(index, pair) {
  // Split the pair by colon to get the key and value
  var keyValue = pair.split(':');

  // Trim any leading or trailing whitespace from the key and value
  var key = $.trim(keyValue[1]);
  var value = $.trim(keyValue[0]);

  // Add the key-value pair to the data object
  data[key] = value;
});

console.log(data);

This code will output the following object:

JavaScript:
{
  'One': '1',
  'Two': '2'
}

Hope this helps!
 

Similar threads

Back
Top