0

I have a string like so

let s = "key e3093e239o0303eje2309\nkey 2390923239239023\nobject 94238923892332\nfile 329239083290239023";

This was JSONstringify'd from a file. I need to organize this data into {key:value} objects and separate them. For example, I need

{key: e3093e239o0303eje2309} and {object: "94238923892332"}

and so on.

I'm thinking the best (and unfortunately long) way of doing it is by breaking the string down.

Assuming every digit combination after 'key' is 40 characters long, is there a way i can remove every character [41] indexes after the last occurrence of 'key'? So the pointer will move 41 places to the right of key (accounting for the space) and remove everything after it?

Additionally, if possible, can I remove everything before the first occurrence of 'object' and everything [41] places after the last occurrence of object and so on?

Not sure if I'm thinking about this the right way...

Edric
  • 24,639
  • 13
  • 81
  • 91
nodumbqs
  • 91
  • 1
  • 6

2 Answers2

1

You can do something like this splitting the string with \n and then getting the key-value pairs

var s = "key e3093e239o0303eje2309\nkey 2390923239239023\nobject 94238923892332\nfile 329239083290239023"


stringToObj = () => {
    var arr = []

    s.split('\n').forEach(e => {
        let obj = {}
        obj[e.split(' ')[0]] = e.split(' ')[1]
        arr.push(obj)
    })

    return arr
}


let pairs = stringToObj(s)
console.log(pairs)


Rahul Pal
  • 476
  • 3
  • 10
1

Tried to use only simple for/loop for performance

const s = "key e3093e239o0303eje2309\nkey 2390923239239023\nobject 94238923892332\nfile 329239083290239023";
const finalObject = {};
let isKey = true;
let currentValue = '';
let currentKey = '';
for (let i = 0; i < s.length; i++) {
  const char = s[i];
  if ('\n' === char) {
    finalObject[currentKey] = currentValue;
    isKey = true;
    currentValue = '';
    currentKey = '';
  } else if (' ' === char) {
    finalObject[currentKey] = currentValue;
    isKey = false;
  } else {
    isKey ? currentKey+=char : currentValue+=char;
  }
}

finalObject[currentKey] = currentValue;

console.log(finalObject);
Eduard
  • 1,768
  • 2
  • 10
  • 14