Skip to content

renameFields(arrayObject|object,newKeys,query)

Bhumil Sarvaiya edited this page Aug 30, 2017 · 1 revision

This function is used to rename fields in array of objects or single object.

Selective renaming can also be done based on the query passed.

If query is passed alongside array of objects, renaming will be done only on the objects which satisfy the condition.

If query is passed alongside single object, renaming will be done only if the object satisfy the condition.

In case of any key not previously present in the object, new key will be added with null value

examples

//common data
var daex = require('./index')
var obj = [
  {
    name: 'abc',
    type: 'array',
    age: 20
  },
  {
    name: 'pqr',
    type: 'string',
    age: 20
  },
  {
    name: 'xyz',
    type: 'array',
    age: 22
  },
  {
    name: 'ghi',
    type: 'array',
    age: 20
  },
  {
    name: 'mno',
    type: 'number',
    age: 20
  }
]
//e.g. 1
daex.renameFields(obj,{'type':'tt'})
console.log(obj)

//Output:
//[ { name: 'abc', age: 20, tt: 'array' },
//  { name: 'pqr', age: 20, tt: 'string' },
//  { name: 'xyz', age: 22, tt: 'array' },
//  { name: 'ghi', age: 20, tt: 'array' },
//  { name: 'mno', age: 20, tt: 'number' } ]
//e.g. 2
daex.renameFields(obj,{'type':'tt'},{'type':'array'})
console.log(obj)

//Output:
//[ { name: 'abc', age: 20, tt: 'array' },
//  { name: 'pqr', type: 'string', age: 20 },
//  { name: 'xyz', age: 22, tt: 'array' },
//  { name: 'ghi', age: 20, tt: 'array' },
//  { name: 'mno', type: 'number', age: 20 } ]
//e.g. 3
daex.renameFields(obj[0],{'type':'tt'})
console.log(obj)

//Output:
//[ { name: 'abc', age: 20, tt: 'array' },
//  { name: 'pqr', type: 'string', age: 20 },
//  { name: 'xyz', type: 'array', age: 22 },
//  { name: 'ghi', type: 'array', age: 20 },
//  { name: 'mno', type: 'number', age: 20 } ]
//e.g. 4
daex.renameFields(obj[1],{'type':'tt'},{'type':'array'})
console.log(obj)

//Output:
//[ { name: 'abc', type: 'array', age: 20 },
//  { name: 'pqr', type: 'string', age: 20 },
//  { name: 'xyz', type: 'array', age: 22 },
//  { name: 'ghi', type: 'array', age: 20 },
//  { name: 'mno', type: 'number', age: 20 } ]

//i.e. no change as obj[1] does not satisfy the query: {'type':'array'}