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

Changing the keys in array of objects || javascript - Stack Overflow

programmeradmin2浏览0评论

I have an array of objects from some api call. Each of these objects have a key named id. I want to change this id to post_id for each object in the array The first key in each object is id, so I have accessed index 0 in the code below.

Thanks in advance.

function changePostId(receivedData) {
  receivedData.forEach(obj => {
    var keys = Object.keys(obj);
    var key = keys[0].replace(/^id/, "post_id");
    tmp[key] = obj[keys[0]];  
  });
}

I have an array of objects from some api call. Each of these objects have a key named id. I want to change this id to post_id for each object in the array The first key in each object is id, so I have accessed index 0 in the code below.

Thanks in advance.

function changePostId(receivedData) {
  receivedData.forEach(obj => {
    var keys = Object.keys(obj);
    var key = keys[0].replace(/^id/, "post_id");
    tmp[key] = obj[keys[0]];  
  });
}
Share Improve this question edited Mar 13, 2021 at 21:58 daformat 7865 silver badges22 bronze badges asked Mar 31, 2019 at 10:24 Bijitashya BirinchiBijitashya Birinchi 913 silver badges8 bronze badges 2
  • it is obj not temp. – Jonas Wilms Commented Mar 31, 2019 at 10:25
  • Yes I have changed that – Bijitashya Birinchi Commented Mar 31, 2019 at 10:26
Add a ment  | 

4 Answers 4

Reset to default 4

You can use map() and Spread Operator. Return the object with rest properties and post_id equal to id of the object.

let arr = [
  {id:0,other:"elm 1"},
  {id:1,other:"elm 2"},
  {id:2,other:"elm 3"},
]
let res = arr.map(({id,...rest}) => ({post_id:id,...rest}));

console.log(res);

Using delete

If you want to modify the original data you can use delete

let arr = [
  {id:0,other:"elm 1"},
  {id:1,other:"elm 2"},
  {id:2,other:"elm 3"},
]
arr.forEach(item => {
  item.post_id = item.id;
  delete item.id;
})

console.log(arr);

You are really making things too plicated. You don't have to work with Object.keys, just access .id:

for(const obj of receivedData) {
  obj.post_id = obj.id;
  delete obj.id;
}

access the id key from the object and assign it to new key (post_id) and then delete the post_id.

receivedData.forEach(obj => {
  obj.post_id = obj.id;
  delete obj.id;
})

Updating the keys array won't update the object itself.

What you need to do is:

  1. create property post_id and assign the obj.id value
  2. delete the obj.id property
function changePostId(receivedData) {
  receivedData.forEach(obj => {
    obj.post_id = obj.id;
    delete obj.id;
  });
}
发布评论

评论列表(0)

  1. 暂无评论