Ad
What Is The Best Way In JavaScript To Trim Down The Properties Of An Object?
Situation:
I have an object like
{ prop_1 : val_1, prop_2 : val_2, prop_3 : val_3 , ..., prop_N : val_N }
and I want to remove all properties that aren't prop_i
, prop_j
or prop_K
?
What is the best way to do this other than the "brute force" way of
var original = { prop_1 : val_1, prop_2 : val_2, prop_3 : val_3 , ..., prop_N : val_N };
var newguy = { prop_i : original.prop_i, prop_j : original.prop_j, prop_k : original.prop_k };
original = newguy;
????
Ad
Answer
Well you can do a function to help you do that.
(function() {
'use strict';
function copyOnly(obj, keysToPreserve) {
var result = {};
for (var i = 0, length = keysToPreserve.length; i < length; ++i) {
var key = keysToPreserve[i];
result[key] = obj[key];
}
return result;
}
function copyExclude(obj, keysToExclude) {
var result = {};
for (var key in obj) {
if (obj.hasOwnProperty(key) && keysToExclude.indexOf(key) === -1) { // -1 means key doesn't exist in keysToExclude
result[key] = obj[key];
}
}
return result;
}
var original = {
a: '1',
b: '2',
c: '3',
d: '4',
e: '5'
};
var toPreserve = ['a', 'b', 'c'];
var result1 = copyOnly(original, toPreserve);
var toExclude = ['d', 'e'];
var result2 = copyExclude(original, toExclude);
// result1 will have the same structure as result2
document.getElementById('result').innerHTML = 'result1 = ' + JSON.stringify(result1) + '\n' + 'result2 = ' + JSON.stringify(result2);
})();
<pre id="result"></pre>
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad