1

I have input boxes ID labeled with the prefix "add-product-" and I want to replace the "add-product-" with nothing. So I tried using data[field.id].replace("add-product-", ""); but it gives me the error: [Error] TypeError: undefined is not an object (evaluating 'data[field.id].replace')

Here is my code:

function addproduct(){

    var datafeilds = Array.from(document.querySelectorAll("[id^='add-product-']"));
    var data = {};
    datafeilds.forEach(function(field){
        data[field.id].replace("add-product-", "");
        data[field.id] = field.value;
    });

    console.log(data);
}

The output is:

[Log] {add-product-name: "", add-product-overlay1: "", add-product-overlay2: "", add-product-wholesale_price: "", add-product-delivery_price: "", …}

I want it to be:

[Log] {name: "", overlay1: "", overlay2: "", wholesale_price: "", delivery_price: "", …}
Always Helping
  • 14,316
  • 4
  • 13
  • 29
tony
  • 506
  • 2
  • 17

2 Answers2

1

You can use replace before the you add into the empty obj again. Also you do not need to use Array.From in your datafeilds as querySelectorAll returns all the nodes in an array by default.

Run snippet below to see it working and all replaced.

function addproduct() {

  var datafeilds = document.querySelectorAll("[id^='add-product-']")
  var data = {};
  datafeilds.forEach(function(field) {
    //replace all add-products with ""
    var replace = field.id.replace("add-product-", "");
    //Push to data {}
    data[replace] = field.value

  });
  console.log(data)
}

addproduct()
<input id='add-product-name' value="1" />
<input id='add-product-overlay1' value="1" />

<input id='add-product-overlay2' value="1" />
<input id='add-product-wholesale_price' value="1" />
<input id='add-product-delivery_price' value="1" />
Always Helping
  • 14,316
  • 4
  • 13
  • 29
  • The code snippet you posted doesn't work... the 1's are being displayed. – tony Jul 28 '20 at 02:45
  • No... it's not...: { "name": "", "overlay1": "", "overlay2": "", "wholesale_price": "", "delivery_price": "" } they should have "1"'s in there. The values aren't coming though. – tony Jul 28 '20 at 02:47
  • @tony Can you clarify what you want ? This is what you said `I want it to be:` - Exactly thats how it being display in `console.log` – Always Helping Jul 28 '20 at 02:48
  • "name": "" - > "name": "1" – tony Jul 28 '20 at 02:49
-1

your data object is empty , so accessing field.id property on it will return undefined. So you are getting the above error.

Regarding prefix id you can achieve by making document.querySelectorAll("input[id^='prefixvalue']")

Asutosh
  • 1,775
  • 2
  • 15
  • 22