🦥
JavaScriptのオブジェクト,配列操作まとめメモ
あれ何だったっけと思うたびに色々なところを調べて方法の新旧や実行効率等に右往左往するのが面倒すぎたので思い出し用メモを作りました。思い出し用のためあまり説明は書いていません。また、現時点の情報のため今後変更になる可能性があります。
オブジェクトの操作
// obj: an object
// key: an property name of object
// val: an property value of object's key
// copy
obj2 = { ...obj }; // shallow
obj2 = structuredClone(obj); // deep (func is not supported)
// merge properties
Object.assign(obj, fromObj1, ...); // destructive; same key is overwritten by right side args
obj2 = {...obj, ...fromObj1}; // non-destructive
// cast from object
ary = Object.entries(obj); // [[key1, val1], [key2, val2], ...]
ary = Object.keys(obj); // [key1, key2, ...]
ary = Object.values(obj); // [val1, val2, ...]
str = JSON.stringify(obj); // to JSON string
map = new Map(Object.entries(obj));
// cast to object
obj = Object.fromEntries(iterable); // iterable is array, hashmap, etc.
obj = JSON.parse(str); // from JSON string
// check existence
bool = Object.hasOwn(obj, key); // key
bool = Object.values(obj).includes(val); // val
num = Object.keys(obj).length; // count of keys
// get val,key from key,val
val = obj.key;
key = Object.keys(obj).find(key => obj[key] === val);
// add key
obj.newKey = foo; // add destructive
obj2 = { newKey: foo, ...obj }; // add non-destructive
// remove key
delete obj.key; // remove destructive
let { key: _, ...obj2 } = obj; // remove non-destructive (hmm... newly created "_" var)
// others
// is plain object or not
bool = (obj !== null && typeof obj === "object" && obj.constructor == Object);
// filter properties ("keys" is string[])
obj2 = Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)))
// restrict key operation (destructive)
Object.freeze(obj); // can't add/remove key and update val
Object.seal(obj); // can't add/remove key, can update val
Object.preventExtensions(obj); // can't add key, can remove and update val
配列の操作
// ary: an array
// idx: an index of array
// val: a value of array at idx
// x: each value of array
// initialize by same values
ary = Array(idx).fill(val); // for primitive
ary = Array(idx).fill().map(() => ({})); // for object (make instance separately)
// copy
ary2 = [ ...ary ]; // shallow
ary2 = structuredClone(ary); // deep (func is not supported)
// merge arrays
ary0 = ary.concat(ary2, ary3, ...); // non-destructive
// cast from array
str = ary.join(",");
set = new Set(ary);
// cast to array
ary = str.split(",");
ary = JSON.parse(str); // from JSON string
ary = Object.entries(obj); // [[key1, val1], [key2, val2], ...]
ary = Object.keys(obj); // [key1, key2, ...]
ary = Object.values(obj); // [val1, val2, ...]
// check existence
bool = ary.includes(val); // val
num = ary.length; // count of idx
bool = ary.some(x => x > foo); // val match the condition, at least one
bool = ary.every(x => x > foo); // all val match the condition
// get val from idx
val = ary[idx]; // 0 <= idx < ary.length; otherwise undefined
val = ary.at(idx); // -ary.length <= idx < ary.length; ary.at(-1) is end val of ary
val = ary.find(x => x > foo); // first val matching the condition
// get idx from val
idx = ary.findIndex(x => x === foo); // first index of matching the condition
// add val
ary.push(foo); // to last; destructive
ary.unshift(foo); // to first; destructive
ary.splice(idx, 0, foo); // to idx; destructive
ary2 = [...ary, foo]; // to last; non-destructive
ary2 = [foo, ...ary]; // to first; non-destructive
ary2 = ary.toSpliced(idx, 0, foo); // add to idx non-destructive
// remove val
val = ary.pop(); // from last; destructive
val = ary.shift(); // from first; destructive
val = ary.splice(idx, 1); // from idx; destructive
ary2 = ary.slice(-(ary.length-1)); // from last; non-destructive
ary2 = ary.slice(1); // from first; non-destructive
ary2 = ary.toSpliced(idx, 1); // from idx; non-destructive
// update val
ary[idx] = foo; // destructive
ary2 = ary.with(idx, foo); // non-destructive
// cleaning array (non-destructive)
ary2 = ary.filter((x,i) => x !== foo); // get vals matching the condition
ary2 = ary.map((x,i) => x<foo ? x*bar : x); // adjust vals by func
ary2 = Array.from(new Set(ary)); // remove duplicates
ary2 = ary.flat(Infinity); // flatten jag array
// reorder sequence
ary.reverse(); // reverse; destructive
ary2 = ary.toReversed(); // reverse; non-destructive
ary.sort(); // sort num ascending; destructive
ary.sort().reverse(); // sort num descending; destructive
ary.sort((x,y) => x.localeCompare(y)); // sort str ascending; destructive
ary.sort((x,y) => y.localeCompare(x)); // sort str descending; destructive
ary.sort((x,y) => x.key - y.key); // sort obj ascending; destructive
ary.sort((x,y) => y.key - x.key); // sort obj descending; destructive
ary2 = ary.toSorted(); // sort num ascending; non-destructive
// sort() of above can be replaced to toSorted() that is non-destructive
// compare
bool = ary.length === ary2.length && ary.every((x,i) => x === ary2[i]); // equivalence
ary0 = ary.filter(x => ary2.indexOf(x) < 0); // difference; only work with unique array
// others
// is array or not
bool = Array.isArray(ary);
// process by each val
ary.forEach((x,i) => func(x));
// fold each val to one value
foo = ary.reduce((acc, x) => acc+x, init);
// grouping by function
obj = Object.groupBy(objAry, x => x.id>9 ? "big" : "sml"); // {sml: [{id: 3}], big: [{id: 10},{id: 77}]}
// like zip function
ary3 = Array.from(ary.keys().filter(i => i<ary2.length).map(i => [ary[i],ary2[i]]));
どうでもいい話
大昔はJavascript表記が主流だった気がするのですが、いつからJavaScriptが主流になったのかなぁ
Discussion
mmn