Object.keys.map does't return the original keys

I'm getting an object from my database: example:

{availability: null
bio: null
category: ""
createdAt: "2020-10-13T13:47:29.495Z"
email: "[email protected]"
firstName: "Lorenzo"
id: 37
image: null
job: null
lastName: "Del Rosario"
location: ""
password: "$2b$10$J6m71nc8gBXTvEENMwBjt.azNitCsna3LsxaDIUg.B0ztiTm5xFea"
phone: ""
skills: null
updatedAt: "2020-10-13T13:47:29.495Z"
website: ""}

I'm trying to map through this object to change all the null values to ''.

This is my code:

const [userData, setUserData] = useState()

useEffect( ()=>{
    
  const fetchData = async () => {
    const a = await getUserData(userId);//this retuns the object
    const cleanUserData = Object.entries(a).map(([key, value]) =>
      value === null || undefined ? value = '' : value
    )
    setUserData(cleanUserData);
  };
  fetchData();
},[])

but in this way i change my values but i loose my keys and the result is an object like this:


{0:37
1:"[email protected]"
2:"$2b$10$J6m71nc8gBXTvEENMwBjt.azNitCsna3LsxaDIUg.B0ztiTm5xFea"
3:"Lorenzo"
4:"Del Rosario"
5:""
6:""
7:""
8:""
9:""
10:""
11:""
12
...}

Upvotes: 1

Views: 1487

Answers (5)

kind user
kind user

Reputation: 41893

You may need to use e.g. Object.fromEntries to recreate the main object after mapping.

const o = {availability: null, bio: null, category: '', createdAt: "2020-10-13T13:47:29.495Z", email: "[email protected]", firstName: "Lorenzo", id: 37, image: null, job: null, lastName: "Del Rosario", location: "", password: "$2b$10$J6m71nc8gBXTvEENMwBjt.azNitCsna3LsxaDIUg.B0ztiTm5xFea", phone: '', skills: null, updatedAt: "2020-10-13T13:47:29.495Z", website: "",};

const res = Object.fromEntries(
   Object.entries(o).map(([key, val]) => [key, val ?? '']),
);

console.log(res);
// then set the state -> setUserData(res);

Upvotes: 3

Naren
Naren

Reputation: 4480

Simple, you can use map reduce functions to get your results.

const obj = {
  "availability": null,
  "bio": null,
  "category": "",
  "createdAt": "2020-10-13T13:47:29.495Z",
  "email": "[email protected]",
  "firstName": "Lorenzo",
  "id": 37,
  "image": null,
  "job": null,
  "lastName": "Del Rosario",
  "location": "",
  "password": "$2b$10$J6m71nc8gBXTvEENMwBjt.azNitCsna3LsxaDIUg.B0ztiTm5xFea",
  "phone": "",
  "skills": null,
  "updatedAt": "2020-10-13T13:47:29.495Z",
  "website": ""
}

const result = Object.keys(obj).reduce((acc, curr) => {
    acc[curr] = (obj[curr] === null || obj[curr] === undefined)  ? '' : obj[curr]
    return acc;
}, {})

console.log(result)

Upvotes: 1

Odinn
Odinn

Reputation: 1106

Please check this solution

 Object.keys(x).reduce((acc, key)=> {
    acc[key] = x[key] === null ? '' : x[key];
    return acc;
    }, {})

P.S.

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

That's why you receive an index instead of the real key

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

Both Object.entries and Object.keys return an array, so when you use map on that the result will be an array. Use reduce instead to create the new object like so:

const cleanUserData = Object.entries(a).reduce((acc, [key, value]) => {
  acc[key] = value == null ? '' : value;
  return acc;
}, {});

Note: Your original test value === null || undefined is not correct because that's not how you test against two possible values, it should be value === null || value === undefined. Also the test value == null (using the double-equal ==) is sufficient as undefined == null in javascript.

Demo:

const a = {availability: null, bio: null, category: "", createdAt: "2020-10-13T13:47:29.495Z", email: "[email protected]", firstName: "Lorenzo", id: 37, image: null, job: null, lastName: "Del Rosario", location: "", password: "$2b$10$J6m71nc8gBXTvEENMwBjt.azNitCsna3LsxaDIUg.B0ztiTm5xFea", phone: "", skills: null, updatedAt: "2020-10-13T13:47:29.495Z", website: ""};

const cleanUserData = Object.entries(a).reduce((acc, [key, value]) => {
  acc[key] = value == null ? '' : value;
  return acc;
}, {});

console.log(cleanUserData);

Upvotes: 7

Greedo
Greedo

Reputation: 3549

Here is a possible solution by copying the object:

const data ={
  availability: null,
  bio: null,
  category: "",
  createdAt: "2020-10-13T13:47:29.495Z",
  email: "[email protected]",
  firstName: "Lorenzo",
  id: 37,
  image: null,
  job: null,
  lastName: "Del Rosario",
  location: "",
  password: "$2b$10$J6m71nc8gBXTvEENMwBjt.azNitCsna3LsxaDIUg.B0ztiTm5xFea",
  phone: "",
  skills: null,
  updatedAt: "2020-10-13T13:47:29.495Z",
  website: ""
}; 


let cleanUserData = (data) => {
    const cleanData = {};
    Object.keys(data).forEach((key) =>
      cleanData[key] = data[key] === null ? '' : data[key]
    )
    return cleanData;
  };

console.log(cleanUserData(data));

Upvotes: 1

Related Questions