最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Assign default value to object if value is undefined - Stack Overflow

programmeradmin6浏览0评论

I'm fetching data from an API, some fields are not required therefore undefined in the response object

I would like to assign a default empty value like null '' [] to my object parameters if said fields are undefined in the response, so far here's what I have (I have more more fields to fetch but stopped at 5 for this example)

await axios.get('').then( async (response) => {
    await Promise.all(response.data.map(async (merce) => {

      let options = {
        // BASE INFO
        field1: merce.field1[0].value,
        field2 : merce.field2[0].value,
        field3 : merce.field3[0].value,
        field4 : merce.field4[0].value,
        field5 : merce.field5[0].value,
      }

      const default_options = {
        // BASE INFO
        field1: null,
        field2 : '',
        field3 : '',
        field4 : [],
        field5 : null,
      }

      const merceObj = Object.assign({}, default_options, options)
    }));

  });

I get an error if a field has no value for instance merce.field2[0] is undefined because the API response doesn't include it, what I'm looking for would be an efficient way to do something like

field2 : if(merce.field2[0].value) { merce.field2[0].value } else {''}

Since I have a lot of fields I don't really wish to do have a lot of if in my code the only thing I could find that could help me is Object.assign() but it didn't help much

I'm fetching data from an API, some fields are not required therefore undefined in the response object

I would like to assign a default empty value like null '' [] to my object parameters if said fields are undefined in the response, so far here's what I have (I have more more fields to fetch but stopped at 5 for this example)

await axios.get('https://myurl.').then( async (response) => {
    await Promise.all(response.data.map(async (merce) => {

      let options = {
        // BASE INFO
        field1: merce.field1[0].value,
        field2 : merce.field2[0].value,
        field3 : merce.field3[0].value,
        field4 : merce.field4[0].value,
        field5 : merce.field5[0].value,
      }

      const default_options = {
        // BASE INFO
        field1: null,
        field2 : '',
        field3 : '',
        field4 : [],
        field5 : null,
      }

      const merceObj = Object.assign({}, default_options, options)
    }));

  });

I get an error if a field has no value for instance merce.field2[0] is undefined because the API response doesn't include it, what I'm looking for would be an efficient way to do something like

field2 : if(merce.field2[0].value) { merce.field2[0].value } else {''}

Since I have a lot of fields I don't really wish to do have a lot of if in my code the only thing I could find that could help me is Object.assign() but it didn't help much

Share Improve this question asked Dec 24, 2021 at 8:32 XanthousXanthous 6525 silver badges16 bronze badges 2
  • how about optional chaining, merce.field2[0]?.value – ProDec Commented Dec 24, 2021 at 8:35
  • 1 merce.field2[0] ?? "" developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Keith Commented Dec 24, 2021 at 8:39
Add a ment  | 

5 Answers 5

Reset to default 3

You can use Conditional (ternary) operator.

Syntax: condition ? exprIfTrue : exprIfFalse

  let options = {
    field1: merce.field1[0].value ? merce.field1[0].value : '',
    ...
  }

Have a look into using @babel/plugin-proposal-optional-chaining this would allow you to do something such as:

const field1 = merce?.field1[0]?.value

You could also look into _.get:

const field1 = _.get(merce, 'field[0].value', null)

If not you'll have to do something a little more cluttered:

merce && merce.field1 && merce.field1.length
  ? merce.field1[0].value
  : undefined

the idea you laking is to loop the first object and assign your default options dynamically

let options = {
        // BASE INFO
        field1: merce.field1[0].value,
        field2 : merce.field2[0].value,
        field3 : merce.field3[0].value,
        field4 : merce.field4[0].value,
        field5 : merce.field5[0].value,
      }
const default_options = {
        // BASE INFO
        field1: null,
        field2 : '',
        field3 : '',
        field4 : [],
        field5 : null,
      }
for (const fieldKey in options) {
  if(!options[fieldKey])
    options[fieldKey] = default_options[fieldKey] // dynamically change it
}

shortest default assignment would be to use || or ?? logical operators:

let options = {
  field1: merce.field1[0].value || null,
  field2 : merce.field2[0].value || '',
  field3 : merce.field3[0].value || '',
  field4 : merce.field4[0].value || [],
  field5 : merce.field5[0].value || null,
}

More about when to use which can be read in this Stacokverflow thread

let options = {
    field1: merce.field1[0].value ?? '',
    ...
  }

?? operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

发布评论

评论列表(0)

  1. 暂无评论