用数组包装字符串类型的对象属性 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/15 11:56:17

为此,请使用 Object.keys() 和 reduce()。为了显示结果,我们还将使用 concat()。

示例

以下是代码 −

var details = { name: ["John", "David"], age1: "21", age2: "23" },
   output = Object
      .keys(details)
      .reduce((obj, tempKey) =>
         (obj[tempKey] = [].concat(details[tempKey]), obj), {})
console.log(output)  

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo302.js。

输出

这将在控制台上产生以下输出 −

PS C:\Users\Amit\javascript-code> node demo302.js
{ name: [ 'John', 'David' ], age1: [ '21' ], age2: [ '23' ] }

相关文章


有用资源