简体   繁体   中英

javascrpt, how could we create an object iterating through two arrays which are the key/value pairs before creating them?

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?

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.

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); 

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)); 

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