简体   繁体   中英

How to change only the first instance of a key in an object

So I've found a number of examples on how to find the first instance of a key in an object, but I haven't been able to find how to both find and only change the name of that first occurrence.

To clarify, I currently have a function that loops through an object and changes property names if they are listed to be changed. Eg 'first_name' be 'firstName', 'customer' be 'individual', etc.

There is also the property 'id' in a number of places, but I only want to change 'id' to 'customerId' for the first instance where 'id' is found.

Basically, I want this object

{
  "id": "12345",
  "location": {
    "id": "400",
    "name": "New York",
  },
 "customer": {
   "id": "2222",
   "first_name": "Bob",
   "last_name": "Jones"
 },
  "address": [
    {
      "line1": "123 Sesame Street",
      "city": "Springfield",
      "country": "US",
      "state": "NY"
     }
  ],
}

to look like

{
  "customerId": "12345",
  "location": {
    "id": "400",
    "name": "New York",
  },
 "individual": {
   "id": "2222",
   "firstName": "Bob",
   "lastName": "Jones"
 },
  "address": [
    {
      "line1": "123 Sesame Street",
      "city": "Springfield",
      "country": "US",
      "state": "NY"
     }
  ],
}

At the moment my function is changing all instances of 'id' into 'customerId', but I only want it to happen for the first 'id' found in the object. My function so far is,

const restructure = obj => {
  Object.fromEntries = arr => Object.assign({}, ...Array.from(arr, ([k, v]) => ({ [k]: v })));
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(restructure);
  }
  return Object.fromEntries(
    Object.entries(obj).map(([key, val]) => [
      keyChanges[key] || key,
      restructure(val),
    ])
  );
};

Where keyChanges is a variable listing what the new names should be changed to if they are found.

const keyChanges = {
  id: 'customerId',
  customer: 'individual',
  first_name: 'firstName',
  middle_name: 'middleName',
  last_name: 'lastName',
};

My attempts to solve this always end up affecting the other instances of 'id' unfortunately. Any pointers will be sincerely appreciated:)

I assume you have something like a mapper which goes over every single item in your array of objects. What you have to do is to add code chunk which will only be executed for the first item in your map function.

For example:

myArrayOfObjects.map((item, index) => {
  if(index == 0) {
    <here goes your function to change the key from "id" to "customerId">
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM