JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id=fred rows=20 cols=60></textarea>
JavaScript
// getSingleKV(undefined) returns undefined
// getSingleKV(null) returns undefined
// getSingleKV({}) returns undefined
// getSingleKV({"aKey":"aValue"}) returns {key:"aKey",value:"aValue"}
// getSingleKV({"aKey" : "aValue","anotherKey":"anotherValue"...}) returns null
function getSingleKV(kvs) {
var r;
if (!kvs) return r
for (var k in kvs) {
if (kvs.hasOwnProperty(k)) {
if (r === undefined) r = {
key: k,
value: kvs[k]
};
else return null;
}
}
return r;
}
// getKVs(undefined) returns undefined
// getKVs(null) returns null
// getKVs({}) returns []
// getKVs({"aKey" : "aValue"}) returns [{key:"aKey",value:"aValue"}]
// getKVs({"aKey" : "aValue","anotherKey":"anotherValue"}) returns [{key:"aKey",value:"aValue"},{key:"anotherKey",value:"anotherValue"}]
// optional second parameter(m==mode) allows you to get an array of (mode===1) keys or (mode===2) values
// eg getKVS(myObject,1)[0] would give you the first key in myObject
// eg getKVS(myObject,2)[3] would give you the value of the fourth key pair in myObject
// eg getKVS(myObject,2).pop() would give you the last value in myObject.
function getKVs(kvs, m) {
var r;
if (!kvs) return kvs;
r = [];
for (var k in kvs) {
if (kvs.hasOwnProperty(k)) {
var v = kvs[k];
r.push(m === 1 ? k : (m === 2 ? v : {
key: k,
value: v
}));
}
}
return r;
}
var txt = "";
function test(fn, fnx, mode) {
txt += fn + (mode ? "(undefined," + mode + ")" : "()") + " ====> " + JSON.stringify(fnx(undefined, mode)) + "\n";
txt += fn + (mode ? "(null," + mode + ")" : "(null)") + " ====> " + JSON.stringify(fnx(null, mode)) + "\n";
txt += fn + (mode ? "({}," + mode + ")" : "({})") + " ====> " + JSON.stringify(fnx({}, mode)) + "\n";
txt += fn + (mode ? "({akey:aValue}," + mode + ")" :...