0

I have the following array of objects:

const pagesByBook = [
{bookName: "An old tome", pages: 123},
{bookName: "Really ancient stuff", pages: 432},
{bookName: "Yup, another old book", pages: 218}
]

And I would like to get the following string output:

        const output= "['An old tome', 123, 'old', null],
        ['Really ancient stuff', 432, 'old', null],
        ['Yup, another old book', 218, 'old', null]"

How can I do this using in a few lines using ES6 methods such as map?

6
  • Maybe. Have you tried anything? DId you get stuck somewhere? Commented Nov 11, 2018 at 18:37
  • You already mentioned the best method...did you try it? Commented Nov 11, 2018 at 18:37
  • Why that weird string format? Can't you just use JSON? Commented Nov 11, 2018 at 18:39
  • Where does that 'old' come from, is that a constant? Commented Nov 11, 2018 at 18:40
  • @Bergi: I guess 'old' could be a constant. Regarding the weird string format, I don't know, because I need to output like a string. I don't know how I could do that with JSON. If it works the same then I'm ok with that possibility. Commented Nov 11, 2018 at 18:46

2 Answers 2

1

This seems to me to be a simple map with ES6 destructuring. Assuming that the last 2 elements in the arrays are constants (old, null):

const data = [ {bookName: "An old tome", pages: 123}, {bookName: "Really ancient stuff", pages: 432}, {bookName: "Yup, another old book", pages: 218} ] 

const result = data.map(({bookName, pages}) => [bookName, pages, 'old', null])

console.log(JSON.stringify(result))

If a string representation of this is needed you could change it to:

const data = [ {bookName: "An old tome", pages: 123}, {bookName: "Really ancient stuff", pages: 432}, {bookName: "Yup, another old book", pages: 218} ] 

const result = data.map(({bookName, pages}) => JSON.stringify([bookName, pages, 'old', null]))

console.log(result.join(','))

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

Comments

0

Use JSON.stringify, Array#map, Object.values, Array#slice and Array#concat to get your required result.

const pagesByBook = [{
    bookName: "An old tome",
    pages: 123
  },
  {
    bookName: "Really ancient stuff",
    pages: 432
  },
  {
    bookName: "Yup, another old book",
    pages: 218
  }
]

const res = JSON.stringify(pagesByBook.map(item => Object.values(item).concat("old", null))).slice(1, -1);

console.log(res)

Comments

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.