/** * Copyright 2024 Resultium LLC * * This file is part of @resultium/utils. * * @resultium/utils is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * @resultium/utils is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RCZ. If not, see . */ /** * Replaces an object from an array with key value object search * * @remarks * This method doesn't support deep comparements. * Vulnerable to generic object injection sink * * @example * ```ts * // prints [{ a: "1", b: "0" }, { a: "2", b: "0" }, { a: "3", b: "lorem" }] * console.log(replaceFromArrayByKeyValue([{ a: "1", b: "0" }, { a: "2", b: "0" }, { a: "3", b: "0" }], { a: "3" }, { b: "lorem" })) * * // prints [{ a: "lorem", b: "0" }, { a: "2", b: "0" }, { a: "3", b: "0" }] * // replaces only the first occurance * console.log(replaceFromArrayByKeyValue([{ a: "1", b: "0" }, { a: "2", b: "0" }, { a: "3", b: "0" }], { b: "0" }, { a: "lorem" })) * ``` * * @param array - array which shall be manipulated with * @param keyValue - key-value object which defines which object shall be removed from the array * @param newObject - object or values to replace within the searched object * @returns modified array */ export const replaceFromArrayByKeyValue = ( array: Array, keyValue: Partial<{ [K in keyof T]: T[K] }>, newObject: Partial<{ [K in keyof T]: T[K] }>, ) => { const keys = Object.keys(keyValue) as Array; const itemIndex = array.findIndex((item) => // eslint-disable-next-line security/detect-object-injection -- warned at remarks keys.every((key) => item[key] === keyValue[key]), ); array[`${itemIndex}`] = { ...array[`${itemIndex}`], ...newObject }; return array; };