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
Add a ment  | 

3 Answers 3

Reset to default 7

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 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