如何将JSON数组转换为JS?

时间:2018-01-11 11:45:11

标签: javascript arrays json

从JSON获取JS对象的语法最优方法是什么? 我有一个描述表单字段的json文件,从中我想获取仅包含name字段值的JS对象,等于null。像这样:

JSON输入:

[
    {
        "name": "firstname",
        "en": "First Name",
        "fr": "Prénom",
        "type": "text"
    },
    {
        "name": "name",
        "en": "Last Name",
        "fr": "Nom",
        "type": "text"
    },
    {
        "name": "email",
        "en": "Email",
        "fr": "Email",
        "type": "text"
    },
    {
        "name": "password",
        "en": "Password",
        "fr": "Mot de Passe",
        "type": "password"
    }
]

Js对象结果:

{
    firstname: null,
    name: null,
    email: null,
    password: null
}

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您可以将Object.assignspread syntax ...用于属性。

var array = [{ name: "firstname", en: "First Name", fr: "Prénom", type: "text" }, { name: "name", en: "Last Name", fr: "Nom", type: "text" }, { name: "email", en: "Email", fr: "Email", type: "text" }, { name: "password", en: "Password", fr: "Mot de Passe", type: "password" }],
    object = Object.assign(...array.map(({ name }) => ({ [name]: null })));
    
console.log(object);

答案 1 :(得分:1)

使用reduce

var output = arr.reduce( ( a, c ) => ( a[c.name] = null, a ),  {} );

<强>演示

&#13;
&#13;
var arr = [{
    "name": "firstname",
    "en": "First Name",
    "fr": "Prénom",
    "type": "text"
  },
  {
    "name": "name",
    "en": "Last Name",
    "fr": "Nom",
    "type": "text"
  },
  {
    "name": "email",
    "en": "Email",
    "fr": "Email",
    "type": "text"
  },
  {
    "name": "password",
    "en": "Password",
    "fr": "Mot de Passe",
    "type": "password"
  }
]

var output = arr.reduce((a, c) => (a[c.name] = null, a), {});
console.log(output);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用array#reduce

var data = [{ "name": "firstname", "en": "First Name", "fr": "Prénom", "type":"text" }, { "name": "name", "en": "Last Name", "fr": "Nom", "type":"text" }, { "name": "email", "en": "Email", "fr": "Email", "type": "text" }, { "name": "password", "en": "Password", "fr":"Mot de Passe", "type":"password" } ],
    result = data.reduce((r, {name}) => (r[name] = null, r), {});
console.log(result);