Javascript

时间:2017-11-17 07:00:39

标签: javascript json object properties

我能否在POST请求中发送元数据?我能够在POST请求中发送大量数据但是如果需要在POST方法中将数据组合在一起并将其发送到REST API,我是否必须操纵正文中的值?

我可以像这样发送:

示例:

{
"name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc",
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"
} 

但我需要发送这样的数据:

示例:

{
"User":{"name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc"},``
"Project":{
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"}
}

1 个答案:

答案 0 :(得分:1)

如果要从当前元数据对象创建新对象,可以像这样初始化新对象:

var res = {
  User: {},
  Project: {}
};

然后您可以使用Object.keys()循环对象键,并弹出结果对象:

Object.keys(obj).forEach(function(key) {
  if (key === "name" || key === "version" || key === "author")
    res.User[key] = obj[key];
  else
    res.Project[key] = obj[key];
});

<强>演示:

var obj = {
  "name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc",
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"
};

var res = {
  User: {},
  Project: {}
};
Object.keys(obj).forEach(function(key) {
  if (key === "name" || key === "version" || key === "author")
    res.User[key] = obj[key];
  else
    res.Project[key] = obj[key];
});
console.log(res);