admin管理员组

文章数量:1433530

I read here that i can add a key:value to an object only if the value is not null otherwise the key:value will not be there at all :

   var product = {
         coverTitle:document.getElementById("coverTitle").value.length>0 ? getElementById("coverTitle").value : undefined,
..
..

Will print :

coverTitle:undefined

I expect to not have this key inside at all.

I read it here : In Javascript, how to conditionally add a member to an object?

answer by Frédéric Hamidi

When uploading to a server I do not want to write this pair at all, like they are not there. What am I doing wrong ?

I read here that i can add a key:value to an object only if the value is not null otherwise the key:value will not be there at all :

   var product = {
         coverTitle:document.getElementById("coverTitle").value.length>0 ? getElementById("coverTitle").value : undefined,
..
..

Will print :

coverTitle:undefined

I expect to not have this key inside at all.

I read it here : In Javascript, how to conditionally add a member to an object?

answer by Frédéric Hamidi

When uploading to a server I do not want to write this pair at all, like they are not there. What am I doing wrong ?

Share Improve this question edited Jun 23, 2019 at 4:35 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Jun 23, 2019 at 4:26 phamngphamng 311 silver badge6 bronze badges 1
  • 1 The link you have posted is with jQuery. It will not work that way without it. – Avin Kavish Commented Jun 23, 2019 at 4:32
Add a ment  | 

2 Answers 2

Reset to default 3

You need to add the property later - undefined key/value pairs are still kept in the object.

let product = {};
const value = document.getElementById("coverTitle").value;
if (value) product.coverTitle = value;

Alternatively, use JSON methods to remove undefined key/value pairs - costly, but it works:

var product = {
     coverTitle: document.getElementById("coverTitle").value.length > 0 ? document.getElementById("coverTitle").value : undefined
};

product = JSON.parse(JSON.stringify(product));

You can conditionally add the key later on, but you can't write it inside the object literal.

  const product = { }

  const value = document.getElementById("coverTitle").value

  if (value)
    product.coverTitle = value

  // or
  value && (product.coverTitle = value)

本文标签: javascriptAdd value to object only if not nullis not workingStack Overflow