对象转换为另一种结构

时间:2018-08-23 15:17:32

标签: javascript jquery javascript-objects

我想将一个对象转换为另一种结构。这是原始对象:

[{
  "id": "2IJXhq",
  "fields": [{
    "key": "FirstName",
    "value": "David"
  }, {
    "key": "LastName",
    "value": "Smith"
  }, {
    "key": "Age",
    "value": 30
  }, {
    "key": "Profession",
    "value": "engineer"
  }, {
    "key": "DOB",
    "value": "1990-03-11"
  }, {
    "key": "Gender",
    "value": "male"
  }]
}, {
  "id": "5BTGyk",
  "fields": [{
    "key": "FirstName",
    "value": "Robert"
  }, {
    "key": "LastName",
    "value": "Conner"
  }, {
    "key": "Age",
    "value": 40
  }, {
    "key": "Profession",
    "value": "doctor"
  }, {
    "key": "DOB",
    "value": "1960-04-22"
  }, {
    "key": "Gender",
    "value": "male"
  }]
}]

我想将其转换为:

[{
  "id": "2IJXhq",
  "person": [{
    "FirstName": "David",
    "LastName": "Smith",
    "Profession": "engineer",
    "Age": 30,
    "DOB": "1990-03-11",
    "Gender": "male"
  }]
}, {
  "id": "5BTGyk",
  "person": [{
    "FirstName": "Robert",
    "LastName": "Conner",
    "Profession": "doctor",
    "Age": 40,
    "DOB": "1990-03-11",
    "Gender": "male"
  }]
}]

有些想法正在尝试使用Map,请按如下所示缩小

let arr = [{"id":"2IJXhq","person":[{"FirstName":"David","LastName":"Smith","Profession":"engineer","Age":30,"DOB":"1990-03-11","Gender":"male"}]},{"id":"5BTGyk","person":[{"FirstName":"Robert","LastName":"Conner","Profession":"doctor","Age":40,"DOB":"1990-03-11","Gender":"male"}]}]
let o = arr.map(item => item.reduce((a, {key, Value}) => ({[key]: Value, ...a} ), {}))

console.log(o)

但这似乎不起作用。

上面的对象正在下面的简单HTML页面中使用。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Concise Handlebars.js</title>
	<link rel="stylesheet" href="style.css">
	<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
	<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.1.2/handlebars.min.js"></script>
</head>
<body>
	<div id="anchor">People
	</div>
	<script id="tpl" type="text/template">
		{{#each this}}
		<div>
			<a href="{{id}}">{{id}} </a>
			{{#each fields}}
			<p>
				{{key}} : {{value}}
			</p>
			{{/each}}
		</div>
		{{/each}}
	</script>
	<script>
		var slingshot = function (url, tplId, anchor) {
     $.getJSON(url, function(data) {
			        console.log(data);
              var template = $(tplId).html();
              var stone = Handlebars.compile(template)(data);
              $(anchor).append(stone);
     });
  }
    slingshot('//api.jsonbin.io/b/5b7eca766376d24455aa55f8', '#tpl', '#anchor');
	</script>
</body>
</html>

5 个答案:

答案 0 :(得分:0)

您可以遍历数组中对象的每个fields属性,并使用reduce()根据对象的原始数组生成一个新对象。试试这个:

arr.forEach(function(item) {
  item.fields = item.fields.reduce(function(obj, item) {
    obj[item.key] = item.value;
    return obj;
  }, {});
});

let arr = [{
  "id": "2IJXhq",
  "fields": [{
    "key": "FirstName",
    "value": "David"
  }, {
    "key": "LastName",
    "value": "Smith"
  }, {
    "key": "Age",
    "value": 30
  }, {
    "key": "Profession",
    "value": "engineer"
  }, {
    "key": "DOB",
    "value": "1990-03-11"
  }, {
    "key": "Gender",
    "value": "male"
  }]
}, {
  "id": "5BTGyk",
  "fields": [{
    "key": "FirstName",
    "value": "Robert"
  }, {
    "key": "LastName",
    "value": "Conner"
  }, {
    "key": "Age",
    "value": 40
  }, {
    "key": "Profession",
    "value": "doctor"
  }, {
    "key": "DOB",
    "value": "1960-04-22"
  }, {
    "key": "Gender",
    "value": "male"
  }]
}]

arr.forEach(function(item) {
  item.fields = item.fields.reduce(function(obj, item) {
    obj[item.key] = item.value;
    return obj;
  }, {});
});

console.log(arr);

答案 1 :(得分:0)

在javascript中添加了注释,详细说明了它正在执行的每个步骤。

var data = [{
    "id": "2IJXhq",
    "fields": [{
        "key": "FirstName",
        "value": "David"
      },
      {
        "key": "LastName",
        "value": "Smith"
      },
      {
        "key": "Age",
        "value": 30
      },
      {
        "key": "Profession",
        "value": "engineer"
      },
      {
        "key": "DOB",
        "value": "1990-03-11"
      },
      {
        "key": "Gender",
        "value": "male"
      }
    ]
  },
  {
    "id": "5BTGyk",
    "fields": [{
        "key": "FirstName",
        "value": "Robert"
      },
      {
        "key": "LastName",
        "value": "Conner"
      },
      {
        "key": "Age",
        "value": 40
      },
      {
        "key": "Profession",
        "value": "doctor"
      },
      {
        "key": "DOB",
        "value": "1960-04-22"
      },
      {
        "key": "Gender",
        "value": "male"
      }
    ]
  }
];

//loop over each data element
data.forEach(function(person){
  //create a new person property from all the fields
  person.person = person.fields.reduce(function(person, fieldObject){
    //put the key value pair on the new person object
    person[fieldObject.key] = fieldObject.value;
    return person;
  }, {});
  
  //remove the old fields property
  delete person.fields;
});

console.log(data);

答案 2 :(得分:0)

您可以使用Array.prototype.mapArray.prototype.reduce生成所需的输出:

const data=[{id:"2IJXhq",fields:[{key:"FirstName",value:"David"},{key:"LastName",value:"Smith"},{key:"Age",value:30},{key:"Profession",value:"engineer"},{key:"DOB",value:"1990-03-11"},{key:"Gender",value:"male"}]},{id:"5BTGyk",fields:[{key:"FirstName",value:"Robert"},{key:"LastName",value:"Conner"},{key:"Age",value:40},{key:"Profession",value:"doctor"},{key:"DOB",value:"1960-04-22"},{key:"Gender",value:"male"}]}];

const result = data.map(({id, fields}) => ({id, person: fields.reduce((all,{key, value}) => (all[key] = value,  all), {})}));

console.log(result);

答案 3 :(得分:0)

您可以尝试使用现有的array.maparray.reduce()

let arr = [{
    "id": "2IJXhq",
    "fields": [{
        "key": "FirstName",
        "value": "David"
      },
      {
        "key": "LastName",
        "value": "Smith"
      },
      {
        "key": "Age",
        "value": 30
      },
      {
        "key": "Profession",
        "value": "engineer"
      },
      {
        "key": "DOB",
        "value": "1990-03-11"
      },
      {
        "key": "Gender",
        "value": "male"
      }
    ]
  },
  {
    "id": "5BTGyk",
    "fields": [{
        "key": "FirstName",
        "value": "Robert"
      },
      {
        "key": "LastName",
        "value": "Conner"
      },
      {
        "key": "Age",
        "value": 40
      },
      {
        "key": "Profession",
        "value": "doctor"
      },
      {
        "key": "DOB",
        "value": "1960-04-22"
      },
      {
        "key": "Gender",
        "value": "male"
      }
    ]
  }
]



let expected = [];
arr.map(function(item, index) {
  expected[index] = {
    'id': item.id
  };
  item.fields = item.fields.reduce(function(obj, item) {
    obj[item.key] = item.value;
    expected[index]['person'] = obj;
    return obj;
  }, {});
});

console.log(expected)

答案 4 :(得分:0)

var arr = [{"id":"2IJXhq","fields":[{"key":"FirstName","value":"David"},{"key":"LastName","value":"Smith"},{"key":"Age","value":30},{"key":"Profession","value":"engineer"},{"key":"DOB","value":"1990-03-11"},{"key":"Gender","value":"male"}]},{"id":"5BTGyk","fields":[{"key":"FirstName","value":"Robert"},{"key":"LastName","value":"Conner"},{"key":"Age","value":40},{"key":"Profession","value":"doctor"},{"key":"DOB","value":"1960-04-22"},{"key":"Gender","value":"male"}]}];

var newMap = arr.map(({ id, fields }) => {
  const person = fields.reduce((person, { key, value }) => ({...person, [key]: value }));
  return { id, person };
});

console.log(newMap);

您可以使用Object.assign({ person, [key]: value })以获得更好的性能。