0

I have one doubt:

I am trying to parse a file which contents are two lines which hold data as:

'Head' 'Heart' 'Hand'
"0 255 5" "100 1 5" "0 55 155"

The first line is a list of body parts, and the second one is a list with each body's parts' gray level.

The need is to create an object like:

atlas = {
    firstName = grayLevel1,
    secondName = grayLevel2,
    ...
};

So then we would have:

atlas = {
    Head = 0 255 5,
    Heart = 100 1 5,
    Hand = 0 55 155,
...
};

I have just managed to read all file, isolate lines and words.

To do that I have written:

readTextFile("columna01-es-latin1.txt");

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
                console.log('The complete text is', allText);
                let lineArr = intoArray(allText);
                let firstLineWords = intoWords(lineArr[0]);
                let secondLineWords = intoWords(lineArr[1]);

                console.log('Our  first line is: ', lineArr[0]);
                for (let i = 0; i < firstLineWords.length; i++) {
                    console.log(`Our ${i} word in the first line is : ${firstLineWords[i]}`);
                    console.log(`Our ${i} word in the SECOND line is : ${secondLineWords[i]}`);
                }


            }
        }
    }
    rawFile.send(null);
}

function intoArray(lines) {
    // splitting all text data into array "\n" is splitting data from each new line
    //and saving each new line as each element*

    var lineArr = lines.split('\n');

    //just to check if it works output lineArr[index] as below


    return lineArr;


}

function intoWords(line) {


    var wordsArr = line.split('" "');


    return wordsArr;
}

To be able to create the object I would do something like:

let atlas = {
                        for(let i = 0; i < firstLineWords.length; i++){
                        firstLineWords[i]: secondLineWords[i]
                        }
                    };

However it is not a valid syntax.

I would do the previous task into readTextFile()

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
                console.log('The complete text is', allText);
                let lineArr = intoArray(allText);
                let firstLineWords = intoWords(lineArr[0]);
                let secondLineWords = intoWords(lineArr[1]);

                console.log('Our  first line is: ', lineArr[0]);
                for (let i = 0; i < firstLineWords.length; i++) {
                    console.log(`Our ${i} word in the first line is : ${firstLineWords[i]}`);
                    console.log(`Our ${i} word in the SECOND line is : ${secondLineWords[i]}`);
                }

                let atlas = {
                    for(let i = 0; i < firstLineWords.length; i++){
                    firstLineWords[i]: secondLineWords[i]
                    }
                };
            }
        }
    }
    rawFile.send(null);
}

I understand that inside an object we can not iterate through properties that have not been created yet.

I have also read:

How to iterate in object properties: Iterate through object properties

Checking objects into arrays:

How do I check if an array includes an object in JavaScript?

Loop thought Objects: How do I loop through or enumerate a JavaScript object?

Adding key/value pairs to object dinamically, it is a very close topic, however Ido not see how it could be applied to this example, ✖:

How can I add a key/value pair to a JavaScript object?

How to iterate into plain Javascript objects: How to Loop through plain JavaScript object with objects as members?

javascript key value pairs: javascript object key value pairs

How could we handle this key/value creation, inside an object?

Yone
  • 2,064
  • 5
  • 25
  • 56
  • Use square bracket notation. `let atlas = {}; for (...) { atlas[firstLineWords[i]] = secondLineWords[I]; }`. – Heretic Monkey Mar 23 '18 at 20:23
  • Possible duplicate of [How to create an object from an Array of key-value pairs?](https://stackoverflow.com/questions/20059995/how-to-create-an-object-from-an-array-of-key-value-pairs) – Heretic Monkey Mar 23 '18 at 20:24
  • 1
    [This looks almost exactly the same as a question you asked earlier today.](https://stackoverflow.com/questions/49451251/javascript-data-structure-to-group-parts-and-graylevel-xml-or-json) – Pointy Mar 23 '18 at 20:24

3 Answers3

1

I believe this solves your problem:

var atlas = {};
for(var i = 0 ; i < bodyParts.length ; i++{
    atlas[bodyParts[i]] = grayLevel[i]
}

Javascript checks if the key exists in atlas and if it doesn't,it creates it and assigns the respective value of greyLevel.

Régis B.
  • 187
  • 1
  • 9
1

Is this what you're looking for? You can reduce the arrays into a single object with key/value pairs equal to the body part and its respective gray levels, like so:

var bodyParts = ['Head', 'Heart', 'Hand'];
var grayLevels = ["0 255 5", "100 1 5", "0 55 155"];

var atlas = bodyParts.reduce(function (res, curr, index) {
  res[curr] = grayLevels[index];
  return res;
}, {});

console.log(atlas);
mhodges
  • 10,938
  • 2
  • 28
  • 46
0

Split the lines, and use Array.map() to get two arrays of the texts you want. Then combine them to an object using Array.reduce():

const text = `'Head' 'Heart' 'Hand'
"0 255 5" "100 1 5" "0 55 155"`;

const txtToObj = (txt) => {
  const [l1, l2] = text.split('\n')
    .map((l) => l.match(/\b[^'"]+/g));
    
  return l1.reduce((r, w, i) => {
    r[w] = l2[i];
    
    return r;
  }, {});
};

console.log(txtToObj(text));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209