简体   繁体   中英

convert string to object js function

I've been trying to answer the following question but have no idea what step comes next. I've tried looking it up but haven't had any luck because most of the answers are in json and I don't know that coding language yet. Below is the question and the code I have so far. Thank you.

Create a function named convertStrToObj() that accepts three string parameters. All three should be optional parameters. If a parameter does not exist set it to 'N/A'. Your function should return an object with three properties first, second, and third. Each of the string parameters should be assigned to that object's properties.

var object = {
  first: '',
  second: '',
  third: ''
};


function convertStringToObject(string1, string2, string3){
   // do something
}

How do I convert a string into an object using vanilla js?

Am I supposed to use booleans?

Is the object variable redundant?

Create an object and assign, checking each parameter.

Your question mentions 'does not exist'. This is unclear as what to do if it is the NULL value.

This example does not enforce that the inputs are strings.

 function convertStrToObj(a, b, c) { const ret = { first: a === undefined || a === null ? 'N/A' : a, second: b === undefined || a === null ? 'N/A' : b, third: c === undefined || a === null ? 'N/A' : c, } return ret; } console.log(convertStrToObj('foo', 'bar', undefined))

 function convertStringToObject(string1, string2, string3) { return { first: string1 ? string1: 'N/A', second: string2 ? string2: 'N/A', third: string3 ? string3: 'N/A' } } let result = convertStringToObject('a', null, 'c'); 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