I have an object:
var obj = { a: 'test1', b: 'test2', c: 'test3', d: 'test4', e: 'test5', f: 'test6', g: 'test7', h: 'test8' }
I want to get result:
res = { a: 'test1', c: 'test3', d: 'test4' }
What is the fastest way to do it?
I have an object:
var obj = { a: 'test1', b: 'test2', c: 'test3', d: 'test4', e: 'test5', f: 'test6', g: 'test7', h: 'test8' }
I want to get result:
res = { a: 'test1', c: 'test3', d: 'test4' }
What is the fastest way to do it?
Directly access the fields:
const res = {a: obj.a, c: obj.c, d: obj.d};
Live Example:
const obj = {
a: "test1",
b: "test2",
c: "test3",
d: "test4",
e: "test5",
f: "test6",
g: "test7",
h: "test8",
};
const res = { a: obj.a, c: obj.c, d: obj.d };
console.log(JSON.stringify(res, null, 4));
In a comment, Himanshu Agrawal asked:
What if the key is unknown and stored in a variable? const keys = ["a", "c", "d"];
I'd probably use a for-of
loop to handle that:
const res = {};
for (const key of keys) {
res[key] = obj[key];
}
Live Example:
const obj = {
a: "test1",
b: "test2",
c: "test3",
d: "test4",
e: "test5",
f: "test6",
g: "test7",
h: "test8",
};
const keys = ["a", "b", "c"];
const res = {};
for (const key of keys) {
res[key] = obj[key];
}
console.log(JSON.stringify(res, null, 4));
But you could also use map
and Object.fromEntries
:
const res = Object.fromEntries(keys.map((key) => [key, obj[key]]));
Live Example:
const obj = {
a: "test1",
b: "test2",
c: "test3",
d: "test4",
e: "test5",
f: "test6",
g: "test7",
h: "test8",
};
const keys = ["a", "b", "c"];
const res = Object.fromEntries(keys.map((key) => [key, obj[key]]));
console.log(JSON.stringify(res, null, 4));
That said, the question asks for the fastest way to do it, and the map
+Object.fromEntries
approach involves several temporary object allocations and function calls. In most cases, it won't matter but the for-of
is probably faster (depending on the degree of optimization the JavaScript engine does). Or a boring old-fashioned for
loop might be faster still:
const res = {};
for (let n = 0; n < keys.length; ++n) {
const key = keys[n];
res[key] = obj[key];
}
Live Example:
const obj = {
a: "test1",
b: "test2",
c: "test3",
d: "test4",
e: "test5",
f: "test6",
g: "test7",
h: "test8",
};
const res = {};
for (let n = 0; n < keys.length; ++n) {
const key = keys[n];
res[key] = obj[key];
}
console.log(JSON.stringify(res, null, 4));
Again, it's unlikely to matter, but it's good to have multiple approaches for situations where it may.
i think you want to delete key-value
pair from the object so for that here's the solution
delete obj[b];
delete obj[e];
or you can use lodash pick
var _ = require('lodash')
_.pick( obj, [a, c, d] )
or create a new Object
var final = {a: obj.a, c: obj.c, d: obj.d}