gpt4 book ai didi

javascript - 如何使用 ES6 方法将这个对象数组转换为字符串?

转载 作者:行者123 更新时间:2023-12-03 00:45:53 25 4
gpt4 key购买 nike

我有以下对象数组:

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

我想得到以下字符串输出:

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

如何使用 ES6 方法(例如 map )在几行中完成此操作?

最佳答案

在我看来,这是一个带有 ES6 解构的简单 map。假设数组中的最后 2 个元素是常量(oldnull):

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

如果需要它的字符串表示,您可以将其更改为:

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(','))

关于javascript - 如何使用 ES6 方法将这个对象数组转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53251878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com