0

How can we convert javascript __proto__ object to a json string output

this.products.forEach(function(element, index) {
  productsInfo.push(productsFormItems[index].myFunction());
});

console.log(JSON.stringify(productsInfo));

myFunction() {
  let result = Object.create({
    ProductName: { value: this.formData.ProductName },
    Address: { value: this.formData.Address }
  });
  return result;
}

See the sample example below:

enter image description here

Required json format:

"productInfo":[
      {
         "ProductName":"Testdata"
         "Address":"TestValue"
      }
  ]
  [
      {
         "ProductName":"Testdata"
         "Address":"TestValue"
      }
  ]
adiga
  • 34,372
  • 9
  • 61
  • 83
Aathira
  • 655
  • 3
  • 14
  • 31
  • 2
    I may be missing something but why do you use `Object.create`? It seems like you always get a new thing anyway, so you can just produce the object. I can't see the reason to play with prototypes here. – VLAZ Mar 02 '20 at 12:51
  • Also, your required format doesn't match what you produce in `.myFunction()`. It's easier to just produce arrays from that method. – VLAZ Mar 02 '20 at 12:53
  • I understood btw I am trying to create a new object with an existing object . The new object doesn't need all the attributes in the existing object. I am not pretty sure what to use thats why used Object.create({ – Aathira Mar 02 '20 at 12:56
  • 1
    It's a bit unclear why `Object.create()` is required. But, for stringifying inherited properties, you can use this: [How to stringify inherited objects to JSON?](https://stackoverflow.com/questions/8779249) – adiga Mar 02 '20 at 12:56
  • 1
    If you want to produce a new object, literally just delete `Object.create` and you are done. [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) will make a new object and assign the parameter you pass in as the *prototype*. So, it's a "create object from this other object". Your literal inside the brackets is already creating a new object, seems you want to just use that. – VLAZ Mar 02 '20 at 13:01
  • @VLAZ You are right and thanks . I have removed the Object.create and its working now. – Aathira Mar 02 '20 at 13:27

0 Answers0