0

I have a txt file that I split by the tabs, then I map out each line to an array. I would like to make these arrays

    [
    "saddle (seat)",
    "asiento"
  ],
  [
    "seat clamp",
    "abrazadera de asiento"
  ],

Into something like this, using Eng and Spa as properties:

{    Eng: saddle (seat),
     Spa: asiento,
     Eng: seat clamp,
     Spa: abrazadera de asiento
}

This is my current code

var fs = require('fs');

var output = fs.readFileSync('component names.txt', 'utf8')
    .replace(/(\r)/gm, "")
    .split('\n')
    .map(line => line.split('\t'))
     /* .reduce(() => {}, )
   components = []
    components[].push({
    Eng: line[0],
    Spa: line[1]
    }) */

console.log('output:', JSON.stringify(output, null, 2));
5
  • 2
    You can't have multiple properties of the same name, the latter ones will overwrite the former ones Commented Nov 3, 2018 at 17:57
  • 1
    Maybe you want and array of objects like: arr= [{Eng: "saddle (seat)", Spa: "asiento"} ,{Eng: "someEng", Spa:"someSpa"}, ...] Commented Nov 3, 2018 at 17:59
  • 1
    zip them together and then map them into an array of objects, Commented Nov 3, 2018 at 18:13
  • 1
    @MarkMeyer yes, can you show me how? Commented Nov 3, 2018 at 18:25
  • @akaphenom can you show me how? Commented Nov 3, 2018 at 18:25

1 Answer 1

2

To get an array of objects, you just need to map() over the lines after you've split() on a \n. Do another split in \t and return the object:

let str = "saddle (seat)\tasiento\nseat clamp\tabrazadera de asiento"
let trans = str.split('\n').map(line => {
    let [Eng, Spa] = line.split('\t')
    return {Eng, Spa}
})
console.log(trans)

// Get all Spa values:
console.log(trans.map(item => item.Spa))

// Get all Eng values:
console.log(trans.map(item => item.Eng))

Edit Based on Comment
You can's just print trans.spa because that could be many values. To get all the Spa values you need to use map to get them all with something like:

trans.map(item => item.Spa)

(added to the excerpt above)

Sign up to request clarification or add additional context in comments.

2 Comments

how do I print out just the Spa values, something like this? console.log(trans.Spa) did not work for me
I've been trying to print out the console.log of the array into an html table, something goes wrong because node is server side. How could I print out the array of Spa into a html table? sorry to bug you again Mark

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.