UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

40 lines (39 loc) 1.55 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.array_change_key_case = array_change_key_case; const _phpTypes_ts_1 = require("../_helpers/_phpTypes.js"); function array_change_key_case(array, cs) { // discuss at: https://locutus.io/php/array_change_key_case/ // original by: Ates Goral (https://magnetiq.com) // improved by: marrtins // improved by: Brett Zamir (https://brett-zamir.me) // example 1: array_change_key_case(42) // returns 1: false // example 2: array_change_key_case([ 3, 5 ]) // returns 2: [3, 5] // example 3: array_change_key_case({ FuBaR: 42 }) // returns 3: {"fubar": 42} // example 4: array_change_key_case({ FuBaR: 42 }, 'CASE_LOWER') // returns 4: {"fubar": 42} // example 5: array_change_key_case({ FuBaR: 42 }, 'CASE_UPPER') // returns 5: {"FUBAR": 42} // example 6: array_change_key_case({ FuBaR: 42 }, 2) // returns 6: {"FUBAR": 42} let result; if (Array.isArray(array)) { result = array; } else if (!array || typeof array !== 'object') { result = false; } else { const caseFunction = cs === undefined || cs === 0 || cs === 'CASE_LOWER' ? 'toLowerCase' : 'toUpperCase'; const source = (0, _phpTypes_ts_1.toPhpArrayObject)(array); const transformed = {}; for (const [key, value] of Object.entries(source)) { transformed[key[caseFunction]()] = value; } result = transformed; } return result; }