简体   繁体   中英

How to create javascript object from concatenated key value pairs

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 ie "": in the object which of course fails for my requirements. How do I do this?

Thanks

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM