admin管理员组文章数量:1279209
I have this Javascript Object as below format but I want to convert it to another format as below: I've pass value form let data = $('#clientForm').serializeArray(); Original format
let data = $('#clientForm').serializeArray();
{ name="addr_types", value="RESID"}
Wanted Format
{addr_types:"RESID"}
Or another format
{"addr_types":"RESID"}
I have this Javascript Object as below format but I want to convert it to another format as below: I've pass value form let data = $('#clientForm').serializeArray(); Original format
let data = $('#clientForm').serializeArray();
{ name="addr_types", value="RESID"}
Wanted Format
{addr_types:"RESID"}
Or another format
{"addr_types":"RESID"}
Share
Improve this question
edited Oct 5, 2016 at 7:48
DMS-KH
asked Oct 5, 2016 at 7:26
DMS-KHDMS-KH
2,7979 gold badges46 silver badges76 bronze badges
4
-
None of your examples are proper objects. Perhaps you meant
{ name:"addr_types", value:"RESID"}
You can have{"addr_types":"RESID"}
– mplungjan Commented Oct 5, 2016 at 7:28 - there are no variables/object in js name=value – madalinivascu Commented Oct 5, 2016 at 7:28
- I've confused now edited – DMS-KH Commented Oct 5, 2016 at 7:30
- and the first "object"? – madalinivascu Commented Oct 5, 2016 at 7:31
3 Answers
Reset to default 7Assuming a valid object, you could just assign the wanted property with the given key/value pair.
var source = { name: "addr_types", value: "RESID" },
target = {};
target[source.name] = source.value;
console.log(target);
ES6 with puted property
var source = { name: "addr_types", value: "RESID" },
target = { [source.name]: source.value };
console.log(target);
Given that your original object is a correct one
var original = {
name: "addr_types",
value: "RESID"
};
console.log(original);
var newName = original.name;
var newValue = original.value;
var newObject = {};
newObject[newName] = newValue;
console.log(newObject);
You can simply do it using .map()
function. bellow is the example.
var original = [{
name: "addr_types",
value: "Work"
},{
name: "village",
value: "Vang Tobang"
},{
name: "mune",
value: "Tang Krasang"
},{
name: "destric",
value: ""
},{
name: "city",
value: "Com Pong Thom"
},{
name: "country",
value: "bodia"
},
];
newArray = original.map(function(item){
return {[item.name]: item.value}
});
If your data container is not array then you can simply create as like bellow.
newArray = [original].map(function(item){
return {[item.name]: item.value}
});
Here is the jsfiddle link: https://jsfiddle/kzrngch6/
本文标签: jqueryHow to change index and value of array object in javascriptStack Overflow
版权声明:本文标题:jquery - How to change index and value of array object in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741303036a2371205.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论