Home > Mobile >  Create an object to access the key and value from another object
Create an object to access the key and value from another object

Time:10-05

I receive the following data in my answer in api

email: Array(1)
0: "The email has already been taken."
length: 1
__ob__: Observer {value: Array(1), dep: Dep, vmCount: 0}
[[Prototype]]: Array
first_name: Array(1)
0: "The first name field is required."
length: 1
__ob__: Observer {value: Array(1), dep: Dep, vmCount: 0}
[[Prototype]]: Array

How could I create an object like that

errors = [{'email':"The email has already been taken."}]

I tried something like this

const object1 = {};
                        let object = this.registerErrors;
                        for(var key in object){
                            object1 = Object.assign({key : object[key]})
                        }
                        console.log(object1)

CodePudding user response:

Try like following snippet :

const registerErrors = {
  email: ["The email has already been taken."],
  first_name: ["The first name field is required."]
}

let object1 = {};
let object = registerErrors;
for(key in object){
    object1[key] = object[key]
}
console.log(object1)

CodePudding user response:

Try this

// Assuming that your error response obj is like
const registerErrors = {
  email: ["The email has already been taken."],
  first_name: ["The first name field is required."]
}

let errors = {};
Object.keys(registerErrors).forEach(key => {
 errors[key]=registerErrors[key][0];
});
console.log(errors);
  • Related