简体   繁体   English

如何将Javascript属性列表转换为对象列表

[英]how can I convert Javascript List of properties to List of objects

I have a list of properties like this 我有这样的属性列表

[{"ID":"0"},{"Day":""},{"Time":""},{"Type":"Both"},{"Status":"false"},
 {"ID":"0"},{"Day":""},{"Time":""},{"Type":"Both"},{"Status":"false"}]

I would like to convert them to something like this 我想将它们转换成这样的东西

[{"ID":"0","Day":"","Time":"","Type":"Both","Status":"false"},
{"ID":"0","Day":"","Time":"","Type":"Both","Status":"false"}]

This is one problem that i face nearly everytime converting a form to json and submitting it to a controller with complex type. 这是我几乎每次将表单转换为json并将其提交给具有复杂类型的控制器时面临的一个问题。

You could check if an object contains the key ID and build a new object with all following objects. 您可以检查对象是否包含密钥ID并使用以下所有对象构建新对象。

 var data = [{ ID: "0" }, { Day: "" }, { Time: "" }, { Type: "Both" }, { Status: "false" }, { ID: "0" }, { Day: "" }, { Time: "" }, { Type: "Both" }, { Status: "false" }], result = data.reduce(function (r, o) { if ('ID' in o) { r.push(Object.assign({}, o)); } else { Object.assign(r[r.length - 1], o); } return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

That is one weird input,.. 这是一个奇怪的输入,..

With the following I'm assuming there is always an ID, and it comes first. 以下我假设总有一个ID,它首先出现。 As that data structure has no way of splitting the properties. 由于该数据结构无法拆分属性。

 var a = [{"ID":"0"},{"Day":""},{"Time":""},{"Type":"Both"},{"Status":"false"}, {"ID":"0"},{"Day":""},{"Time":""},{"Type":"Both"},{"Status":"false"}]; var ret = [], c = null; a.forEach((r) => { if (r.ID) { c = {}; ret.push(c); } let k = Object.keys(r)[0]; c[k] = r[k]; }); console.log(ret); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM