[英]How to change index and value of array object in javascript
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();我有以下格式的 Javascript 对象,但我想将其转换为另一种格式,如下所示:我已传递值形式 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"}
Assuming 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 computed property具有计算属性的 ES6
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.您可以简单地使用.map()
函数来完成。 bellow is the example.下面是例子。
var original = [{
name: "addr_types",
value: "Work"
},{
name: "village",
value: "Vang Tobang"
},{
name: "commune",
value: "Tang Krasang"
},{
name: "destric",
value: ""
},{
name: "city",
value: "Com Pong Thom"
},{
name: "country",
value: "combodia"
},
];
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.net/kzrngch6/这是jsfiddle链接: https : //jsfiddle.net/kzrngch6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.