JavaScript对象文字和ES6 - 将大对象解构为较小对象的合成糖?

时间:2018-02-14 16:43:49

标签: javascript ecmascript-6 object-literal

我想知道的是;是否有一个简单的合成捷径,我想在这里做。

我在循环中有一个大的JSON对象,如下所示:

let line = {
    first_name: ...,
    last_name: ...,
    title: ...,
    email: ...,
    facebook_account: ...,
    linkedin_account: ...,
    twitter_account: ...,
    instagram_account: ...,
    snapchat_account: ...
};

然后我将此有效负载分解为更小的对象:

let profile = {
    first_name: line.first_name,
    last_name: line.last_name,
    title: line.title,
    email: line.email
};

let social = {
    facebook_account: line.facebook_account,
    linkedin_account: line.linkedin_account,
    twitter_account: line.twitter_account,
    instagram_account: line.instagram_account,
    snapchat_account: line.snapchat_account 
};

ES6能否为我提供一种方法来减少每个属性的重复,即first_name,facebook_account等?关于它们如何分解,属性名称不一定是显而易见的 - 它基于我们的数据模型。

这是很多重复的手工作品。我想知道我是否错过了一些ES6魔法,或者其他什么东西,这很漂亮。我真的不是在寻找一个带有机器学习算法的超级聪明的递归循环...如果可能的话,只需要更短的语法。 :)

2 个答案:

答案 0 :(得分:4)

您可以使用对象析构函数:

let {variables} = obj

和单个变量赋值:

let obj2 = { variables }

变量可以是多个,用逗号分隔。

析构函数时:let {name, date, whatever} = obj;

以及分配时:let obj2 = { name, date, whatever }

let line = {
    first_name: "Zak",
    last_name: "Frisch",
    title: "my Title",
    email: "myemail@whatever",
    facebook_account: "fb",
    linkedin_account: "li",
    twitter_account: "tweet",
    instagram_account: "ia",
    snapchat_account: "sc"
};

let {first_name, last_name, title, email, facebook_account, linkedin_account, twitter_account, instagram_account, snapchat_account} = line;

let profile = {
    first_name,
    last_name,
    title,
    email
};

let social = {
    facebook_account,
    linkedin_account,
    twitter_account,
    instagram_account,
    snapchat_account
};
console.log(profile, social);

答案 1 :(得分:1)

根据this回答,你可以这样做:

let line = {
    first_name: "Zak",
    last_name: "Frisch",
    title: "my Title",
    email: "myemail@whatever",
    facebook_account: "fb",
    linkedin_account: "li",
    twitter_account: "tweet",
    instagram_account: "ia",
    snapchat_account: "sc"
};

let profile = Object.keys(line).reduce(function(obj, k) {
  if (!k.endsWith('_account')) obj[k] = line[k];
  return obj;
}, {});

let social = Object.keys(line).reduce(function(obj, k) {
  if (k.endsWith('_account')) obj[k] = line[k];
  return obj;
}, {});

console.log(line);

console.log(profile);

console.log(social);