Create an array containing views with renamed keys for every element in a provided array.
var rekeyViews = require( '@stdlib/array/base/rekey-views' );Returns an array containing views with renamed keys for every element in a provided array.
var x = [
{
'x': 1,
'y': 2
},
{
'x': 3,
'y': 4
}
];
var mapping = {
'x': 'a',
'y': 'b'
};
var out = rekeyViews( x, mapping );
// returns [ <Object>, <Object> ]
var v0 = out[ 0 ].toJSON();
// returns { 'a': 1, 'b': 2 }
var v1 = out[ 1 ].toJSON();
// returns { 'a': 3, 'b': 4 }
// Mutate the first element in the input array:
x[ 0 ].x = 5;
v0 = out[ 0 ].toJSON();
// returns { 'a': 5, 'b': 2 }
// Set a view property:
out[ 1 ].b = 'beep';
v1 = out[ 1 ].toJSON();
// returns { 'a': 3, 'b': 'beep' }
var y = x.slice();
// returns [ { 'x': 5, 'y': 2 }, { 'x': 3, 'y': 'beep' } ]The function has the following parameters:
- arr: input array.
- mapping: object mapping existing keys to new key names.
- The function returns views having only those keys which are present in a provided mapping object. Any keys which are not present in the provided mapping object, but are present in the original objects, are omitted during view creation.
- The function assumes that each object has the keys specified in a provided mapping object.
- Each view in the returned array shares the same memory as the corresponding elements in the input arrays. Accordingly, mutation of either an array element or a view will mutate the other.
var discreteUniform = require( '@stdlib/random/base/discrete-uniform' );
var filledBy = require( '@stdlib/array/base/filled-by' );
var rekeyViews = require( '@stdlib/array/base/rekey-views' );
function clbk( idx ) {
return {
'x': idx,
'y': discreteUniform( 0, 10 )
};
}
var x = filledBy( 10, clbk );
var mapping = {
'x': 'a',
'y': 'b'
};
var out = rekeyViews( x, mapping );
// returns [...]