简体   繁体   中英

How to change the location of an object key value pair in JavaScript

I've seen similar questions to this one but in different languages and I am struggling to create a JavaScript equivalent.

I am receiving an object and through a function I want to change the location of one (or more) of the properties. For example,

With the original object of

{
  individual: [
    {
      dob: '2017-01-01',
      isAuthorized: true,
    },
  ],
  business: [
    {
     taxId: '123',
    },
  ],
  product: {
    code: '123',
  },
}

I would like to change the location of isAuthorized to be in the first object inside of the business array instead of individual .

Like so

{
  individual: [
    {
      dob: '2017-01-01',
    },
  ],
  business: [
    {
     taxId: '123',
     isAuthorized: true,
    },
  ],
  product: {
    code: '123',
  },
}

So far I was trying to create an object that would contain the key name and location to change it to, eg

{
  isAuthorized: obj.business[0]
}

And then loop over the original object as well as the object with the location values and then set the location of that key value pair.

Basically, in this function I want to see that if the original object contains a certain value (in this case isAuthorized ) that it will take that key value pair and move it to the desired location.

What you want can easily be achieved by using loadsh, here's a working snippet of how to restructure based on defined structure map. Extended this example to match what you want.

The example is doing a deep clone, if you are fine modifying the original object then skip that step to avoid the overhead.

 // input data const data = { individual: [ { dob: '2017-01-01', isAuthorized: true, }, ], business: [ { taxId: '123', }, ], product: { code: '123', }, }; // the structure change map const keyMap = { 'individual[0].isAuthorized': 'business[0].isAuthorized' }; function parseData(data,keyMap) { const newData = _.cloneDeep(data); for( let [source,dest] of Object.entries(keyMap) ) { _.set(newData,dest,_.get(newData,source)); _.unset(newData,source); } return newData; } console.log(parseData(data, keyMap));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Note: loadsh's set consider any numeric value as an array index so if you are using a numeric object key then use loadash.setWith. I recommend reading examples in doc for a better understanding. https://lodash.com/docs/4.17.15#set

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