0

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

enter image description here

4
  • None of your examples are proper objects. Perhaps you meant { name:"addr_types", value:"RESID"} You can have {"addr_types":"RESID"} Commented Oct 5, 2016 at 7:28
  • there are no variables/object in js name=value Commented Oct 5, 2016 at 7:28
  • I've confused now edited Commented Oct 5, 2016 at 7:30
  • and the first "object"? Commented Oct 5, 2016 at 7:31

3 Answers 3

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

var source = { name: "addr_types", value: "RESID" },
    target = { [source.name]: source.value };

console.log(target);

Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

Object { name="addr_types", value="WORK"}
No I upvoded not me
@HengSopheak Ok but I still not understand your comment :)
Both answers (as of now) are correct. Nina's is more complete but this was answered in the same minute and is also correct.
1

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: "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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.