最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object.keys.map does't return the original keys - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Oct 26, 2020 at 12:14 Lorenzo Case Del RosarioLorenzo Case Del Rosario 831 silver badge10 bronze badges 2
  • 3 BTW, your api has a major security flaw: the response should not include the password. – ibrahim mahrir Commented Oct 26, 2020 at 12:27
  • Yes, that will be my next step, thank you! – Lorenzo Case Del Rosario Commented Oct 26, 2020 at 14:52
Add a ment  | 

5 Answers 5

Reset to default 7

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

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

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

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

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)

发布评论

评论列表(0)

  1. 暂无评论