Home > database >  how to convert a complex array to object
how to convert a complex array to object

Time:03-16

I have array like this

    [
  'A (1)',
  'B (2)',
  'C (3)',
  'D (6)',
  'E (0)',
  'F(0)'
]

I want convert above array to object like this \

  { A:1,B:2,C:3,D:6,E:0,F:0 }

what is the best way to convert

CodePudding user response:

You can map your array elements into entries format [key, value] and pass that into Object.fromEntries().

One option for extracting the keys and values from your string would be to use a regular expression.

const arr = [
  'A (1)',
  'B (2)',
  'C (3.14159)',
  'non-conformant value just for fun',
  'D (-6)',
  'E (0)',
  'F(0)'
]

const rx = /^(\w ) ?\((-?\d (\.\d )?)\)$/
const obj = Object.fromEntries(
  arr.map(val => val.match(rx)?.slice(1))
    .filter(entry => !!entry)
    .map(([k, v]) => [k, Number(v)])
)

console.log(obj)

This will handle any set of word characters as the key and any numeric expression as the value.

CodePudding user response:

// this should work given that the second last position always contains the digit. Use regex to extract the number value if this isn't working for you.

let arr = [
    'A (1)',
    'B (2)',
    'C (3)',
    'D (6)',
    'E (0)',
    'F(0)'
]

let modArr = new Map(
    arr.map((item) => [item[0], parseInt(item[item.length-2])]
    )
)
let obj = Object.fromEntries(modArr)
console.log(obj)

CodePudding user response:

Array.reduce implementation

var regExp = /\(([^)] )\)/;
const data = [
  'A (1)',
  'B (2)',
  'C (3)',
  'D (6)',
  'E (0)',
  'F(0)'
];
const output = data.reduce((acc, curr) => {
  acc[curr[0]] =  regExp.exec(curr)[1];
  return acc;
}, {});
console.log(output)

CodePudding user response:

var disp = document.getElementById("response");
var x = [
    'A (1)',
    'B (2)',
    'C (3)',
    'D (6)',
    'E (0)',
    'F(0)'
];
var objdata = (arr) => {
    var obj = {};
    arr.forEach((a) => {
        var indArr = a.replace(' ', '').split('(');
        obj[indArr[0]] = indArr[1].replace(')', '');
    });
    return obj;
}
disp.innerHTML = JSON.stringify(objdata(x))
<span id="response"></span>

  • Related