0

I need to create an object from a variable created with concateneated key value pairs. HardCoded (it is an array as dataSource for a jquery datatable), it looks like this:

obj = {
          totalValue: valVar,
          totalReceiptValue: receiptVar
      }
dataSourceArray.push(obj);

My variable is:

cumulator ="totalValue:8573.0000,totalReceiptValue:3573.00,"

I've tried this,

var obj = {};
const name = ""; 
const value = cumulator;
obj[name] = value;
dataSourceArray.push(obj);

but then I have an extra key i.e. "": in the object which of course fails for my requirements. How do I do this?

Thanks

2 Answers 2

1

Assuming that there are no extra : or , signs that could mess with the logic, it can be achieved simply by spliting the strings and using the built in method Object.prototype.fromEntries

const input = "totalValue:8573.0000,totalReceiptValue:3573.00,";

const output = Object.fromEntries( // combine entries into object
  input.split(",") // divide into pairs
  .filter(Boolean) // remove empty elements (comma at the end)
  .map((el) => el.split(":")) // divide the pair into key and value
)

console.log(output)

There apparently being some problems with IE and Edge, the code above can be fixed by writing own implementation of from Entries and opting to not use arrow functions.

const input = "totalValue:8573.0000,totalReceiptValue:3573.00,";

const entries = input.split(",") // divide into pairs

const output = {};
for (let i=0; i<entries.length; i++) {
  if (!entries[i]) continue; // remove empty elements (comma at the end)
  const [key, val] = entries[i].split(":"); // divide the pair into key and value
  output[key]=val; // combine entries into object
}

console.log(output)

Sign up to request clarification or add additional context in comments.

1 Comment

Hi and thanks, but the fat arrow and .fromEntries are not supported by IE and apparently .fromEntries is also an issue with Edge.
0

You can simply use split, map reduce functions.

Try this.

const input = "totalValue:8573.0000,totalReceiptValue:3573.00,";
const result = input.split(',').filter(Boolean).map(function(text) {
 return text.split(':')
}).reduce(function(acc, curr) {
  acc[curr[0]] = curr[1]
  return acc
}, {})

console.log(result)

2 Comments

Thx again, but 'const [key, val]' gives a syntax error in IE with 'Expected identifier'
Got it!! ( output[split[0].trim()] = split[1].trim(); )Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.