简体   繁体   中英

how can I make a string object's value in javascript

 {x : 425, y:25}

我有一个像“425,25”这样的字符串,我需要这样的输出

 {x: 425, y:25}

You can use .split() and .map() functions. Consider the steps mentioned below:

  • Split the input string using .split() function by passing comma , as delimiter.
  • Map the returned array by passing Number function that will convert strings to corresponding numeric values.
  • Use array destructuring to unpack values from returned array in desired variables.
  • Use object literal notation to create an object with these variables.

 let data = "425,25", [x, y] = data.split(",").map(Number), result = {x, y}; console.log(result);

How about that? with ES6 Rename Object Keys in Javascript

 //{x: 425, y:25} const arr = "425,25".split(',').map(Number); //maps value to Number after split const {0: x,1: y} = {...arr}; // make array to object and rename keys ie x,y const result = {x,y} // wrap variable to object console.log(result); // your expected result

You can split a string using the string's .split method . This will give you an array with the two strings '425' and '25' . You can then parse them into integers using parseInt , and create an object with them:

 const input = '425,25'; const substrings = input.split(','); const result = { x: parseInt(substrings[0], 10), y: parseInt(substrings[1], 10), }; console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM