当前位置:网站首页>JS how to convert a string into an array object

JS how to convert a string into an array object

2022-06-12 12:23:00 Cherry*

js How to convert a string into an array object

// The data format is as follows :
list: [
		  {
    
		    radio: "",
		    formInline: "1,2,3,4", // Process this string 
		  },
		  {
    
		    radio: "",
		    formInline: "1,2,3,4",
		  },
],
// First cycle list
let str = this.list;
for(var i = 0;i<str.length;i++){
    
	let arr = str[i].formInline.split(",").map((item)=>{
    
		let obj  = {
    };
		obj.name = item;
		return obj;
	})
	this.list[i].formInline = arr; // take arr Assign to array 
	console.log(this.list[i].formInline);
}
  • split() Method is used to put a A string is split into an array of strings . grammar : stringObject.split(separator,howmany)
  • separator It's necessary . String or regular expression , Split from where specified by this parameter stringObject.
  • howmany Optional . This parameter specifies the maximum length of the returned array . If this parameter is set , No more substrings will be returned than the array specified by this parameter . If the parameter is not set , The entire string will be split , Regardless of its length .
"2:3:4:5".split(":")  // Will return ["2", "3", "4", "5"]
"|a|b|c".split("|")   // Will return ["", "a", "b", "c"]

map() Method to create a new array , The result is that each element in the array is the return value after a call to the supplied function .

const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// Results output :[2, 8, 18, 32]

 Insert picture description here
The same is true if it is a string

let str = "1,2,3,4";
let arr=str.split(',').map(item=>{
    
	let obj = {
    };
	obj.name = item;
	return obj
})
console.log(arr)

give the result as follows :
 Insert picture description here

原网站

版权声明
本文为[Cherry*]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010520406600.html