How can get the property name of an object array value? - javascript

I have an object like below:
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
How can I know the property name "cars" when I input "BMW"? I need a function which needs to return property name "cars" when I pass the argument "BMW" in the function.

function getKeyByitem(myObj, value)
for (var key in myObj) {
if (myObj.hasOwnProperty(key) && Array.isArray(myObj[key])) {
if(myObj[key].indexOf(value) != -1){
return key;
}
}
}
}
var key = getKeyByitem(myObj, 'BMW');
here is demo https://plnkr.co/edit/wVFGcAKuml4rWuIaMx2K?p=preview

myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
var findKey = function (str) {
var keys = Object.getOwnPropertyNames(myObj);
var key = null;
var match = keys.some(function (k) {
key = k;
var val = myObj[key];
if (Array.isArray(val)) {
return val.indexOf(str) >= 0;
} else {
return val.toString() === str;
}
return false;
});
if (match) return key;
}
console.log(findKey('BMW')); // 'cars'
console.log(findKey('John')); // 'name'
console.log(findKey('30')); // 'age'
Hope this helps!

You cna do something like this
var myObj = {
"name": "John",
"age": 30,
"cars": ["Ford", "BMW", "Fiat"]
}
var getKey=function(elem) {
var toReturn = '';
for (var k in myObj) { // loop through the object
if(Array.isArray(myObj[k])){
if(myObj[k].indexOf(elem) !== -1){
toReturn = k;
}
}
else{
if(myObj[k] === elem){
toReturn = k
}
}
}
return toReturn;
}
console.log(getKey('BMW'))
DEMO

Related

Get path to JSON object by key?

Given the following object:
const ourObject = {
"payload": {
"streams": [
{
"children": {
"2165d20a-6276-468f-a02f-1abd65cad618": {
"additionalInformation": {
"narrative": {
"apple": "A",
"banana": "B"
},
"myInventory": {
"fruits": [
{
"name": "apple"
},
{
"name": "banana"
}
]
}
}
}
}
}
]
}
};
We're trying to find the path of myInventory, the issue is that the children's uuid will be different each time. Any idea how we can get the path to myInventory by providing it as a key and get the json path to it?
If things are dynamic, a programmatic key search could help
const ourObject = {
"payload": {
"streams": [
{
"children": {
"2165d20a-6276-468f-a02f-1abd65cad618": {
"additionalInformation": {
"narrative": {
"apple": "A",
"banana": "B"
},
"myInventory": {
"fruits": [
{
"name": "apple"
},
{
"name": "banana"
}
]
}
}
}
}
}
]
}
};
const getPath = (key, o) => {
if (!o || typeof o !== "object") {
return "";
}
const keys = Object.keys(o);
for(let i = 0; i < keys.length; i++) {
if (keys[i] === key ) {
return key;
}
const path = getPath(key, o[keys[i]]);
if (path) {
return keys[i] + "." + path;
}
}
return "";
};
const getValueForKey = (key, o) => {
if (!o || typeof o !== "object") {
return undefined;
}
const keys = Object.keys(o);
for(let i = 0; i < keys.length; i++) {
if (keys[i] === key ) {
return o[key];
}
const value = getValueForKey(key, o[keys[i]]);
if (value) {
return value;
}
}
return undefined;
}
console.log(getPath("myInventory", ourObject))
console.log(getValueForKey("myInventory", ourObject))
Not sure if I understand the question right but
let uuid = '2165d20a-6276-468f-a02f-1abd65cad618';
ourObject.payload.streams[0].children[uuid].additionalInformation.myInventory
var changingKey = Object.keys(ourObject["payload"]["streams"][0]["children"])[0];
console.log(ourObject["payload"]["streams"][0]["children"][changingKey]["additionalInformation"]["myInventory"]);
Okay, you could create a helper function that gets the UUID. Since it's an object, the lookup is close to O(1) especially given the case that the children has only one key-value pair here.
function getUUIDFromPayload(payload) {
let obj = payload.streams[0].children
let uuid = Object.keys(obj)[0]
return uuid
}
Usage
const uuid = getUUIDFromPayload(payload)
ourObject.payload.streams[0].children[uuid].additionalInformation.myInventory

Convert an Object into an Object of Objects

I have an Object:
{
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
}
I want to convert it to:
{
"Results": {
"circle": {
"circle": 0.06879016757011414
},
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": {
"square": 0.8266428709030151
}
}
}
Have tried this code:
var modData = {};
data = data.Results;
for (var key in data) {
if (data.hasOwnProperty(key)) {
modData[key] = data[key];
for (var innerKey in data[key]) {
modData[key] = data[key];
}
}
}
console.log("Modified is:", modData);
Unfortunately, this still returns the original object, what is it that I am doing which is wrong?
A jquery solution is fine as well.
Loop trough the properties with for .. in and any property is not an object replace it with one. Like this:
let x = {
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
}
for (key in x.Results) {
if (typeof x.Results[key] !== 'object')
x.Results[key] = {
[key]: x.Results[key]
}
}
console.log(x);
If you want to preserve the original object do this:
let data = {
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
}
data = data.Results;
modData = {};
for (key in data) {
if (typeof data[key] !== 'object')
modData[key] = { [key]: data[key] }
else
modData[key] = { [key]: data[key] }
}
console.log(modData);
You could check the type and if not an object then assign a new object with the same key and value.
This proposal uses computed property names for getting a variable as key for an object.
var object = { Results: { circle: 0.06879016757011414, quad: { exp: 0.8039023876190186, actual: 0.19609761238098145 }, square: 0.8266428709030151 } };
Object
.keys(object.Results)
.forEach(function (k) {
if (object.Results[k] && typeof object.Results[k] !== 'object') {
object.Results[k] = { [k]: object.Results[k] };
}
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The value that should be stored in modData should be the object itself rather than the value. This code gives the expected value
var modData = {};
data = data.Results;
for (var key in data) {
if (data.hasOwnProperty(key)) {
var temp = Object();
temp[key] = data[key];
modData[key] = temp;
for (var innerKey in data[key]) {
var temp = Object();
temp[key] = data[key];
modData[key] = temp;
}
}
}
const input = {
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
};
const result = {
Results: {}
};
//If you want object construct specifically for "circle" & "square"
for (let key in input.Results) {
if (input.Results.hasOwnProperty(key)) {
if (key === 'circle') {
result.Results.circle = {
'circle': input.Results[key]
}
} else if (key === 'square') {
result.Results.square = {
'square': input.Results[key]
}
} else {
result.Results[key] = input.Results[key];
}
}
}
//Generically construct object if key is not object
for (let key in input.Results) {
if (input.Results.hasOwnProperty(key)) {
if (key !== 'object') {
result.Results[key] = {
[key]: input.Results[key]
}
}
}
}
console.log(result);

Convert a string key in a JSON object to a child object?

I've looped through an document.form.element the names are constructed into an array name like so:
Current output
Some of the names of they keys are like so in JSON:
{
data[name]: "foo",
data[address]: "baz drive",
data[city]: "Dallas",
data[state]: "Texas",
data[phone]: "555-1212"
}
Desired output
Is there a way to convert it to this with Pure JavaScript (and without frameworks like jQuery) without using eval?:
{
data: {
name: "foo",
address: "baz drive",
city: "Dallas",
state: "Texas",
phone: "555-1212"
}
}
What have i tried so far
<script type="javascript">
var o = {
data[name]: "foo",
data[address]: "baz drive",
data[city]: "Dallas",
data[state]: "Texas",
data[phone]: "555-1212"
}
var temp = [];
for (key in o) {
temp[JSON.parse(key)] = o;
}
</script>
Fiddle is here: http://jsfiddle.net/chrisjlee/medbzv9a/
Or is this not totally possible?
Do like
var o = {
"data[name]": "foo",
"data[address]": "baz drive",
"data[city]": "Dallas",
"data[state]": "Texas",
"data[phone]": "555-1212"
};
o.data = {};
for (key in o) {
var index = key.match(/[^[\]]+(?=])/g);
if(index) {
o.data[index] = o[key];
delete(o[key]);
}
}
console.log(o);
Here is a sample fiddle.
The following function should fix the object. It will be executed recursively and it can handle arrays too.
var fixKeys = function(obj) {
if (typeof(obj) != "object")
return obj;
if (Object.prototype.toString.call(obj) == "[object Array]")
return obj.map(arguments.callee);
var newObj = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key))
continue;
var m = /^(\w+)\[(\w+)\]$/.exec(key);
if (m) {
newObj[m[1]] = newObj[m[1]] || {};
newObj[m[1]][m[2]] = arguments.callee(obj[key]);
} else {
newObj[key] = arguments.callee(obj[key]);
}
}
return newObj;
};
Fiddle
And here's an even better version, which can handle data of this type:
var o = {
"data[name]": "foo",
"data[address][street]": "baz drive",
"data[address][city]": "Dallas",
"data[address][state]": "Texas",
"data[phone]": "555-1212",
someArray: [
{"test[a]": 42},
42
]
};
Just in case you need it:
var fixKeys = function(obj) {
if (typeof(obj) != "object")
return obj;
if (Object.prototype.toString.call(obj) == "[object Array]")
return obj.map(arguments.callee);
var newObj = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key))
continue;
var m = /^(\w+)(?:\[\w+\])+$/.exec(key);
if (m) {
var subKey = key.substr(m[1].length);
var subObj = newObj[m[1]] = newObj[m[1]] || {};
while (m = /^\[(\w+)\]\[/.exec(subKey)) {
subObj = subObj[m[1]] = subObj[m[1]] || {};
subKey = subKey.substr(m[0].length - 1);
}
m = /^\[(\w+)\]$/.exec(subKey);
subObj[m[1]] = arguments.callee(obj[key]);
} else {
newObj[key] = arguments.callee(obj[key]);
}
}
return newObj;
};
Fiddle

Change key name in nested JSON structure

I have a JSON data structure as shown below:
{
"name": "World",
"children": [
{ "name": "US",
"children": [
{ "name": "CA" },
{ "name": "NJ" }
]
},
{ "name": "INDIA",
"children": [
{ "name": "OR" },
{ "name": "TN" },
{ "name": "AP" }
]
}
]
};
I need to change the key names from "name" & "children" to say "key" & "value". Any suggestion on how to do that for each key name in this nested structure?
I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question), but if that's removed, then you can use a reviver function to make modifications while parsing the data.
var parsed = JSON.parse(myJSONData, function(k, v) {
if (k === "name")
this.key = v;
else if (k === "children")
this.value = v;
else
return v;
});
DEMO: http://jsfiddle.net/BeSad/
Try this:
function convert(data){
return {
key: data.name,
value: data.children.map(convert);
};
}
Or if you need to support older browsers without map:
function convert(data){
var children = [];
for (var i = 0, len = data.children.length; i < len; i++){
children.push(convert(data.children[i]));
}
return {
key: data.name,
value: children
};
}
You could use a function like this :
function clonerename(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
var newPropName = prop;
if (prop=='name') newPropName='key';
else if (prop=='children') newPropName='value';
clone[newPropName] = clonerename(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = clonerename(A);
Note that what you have isn't a JSON data structure (this doesn't exist as JSON is a data-exchange format) but probably an object you got from a JSON string.

transformation- in to an array

Input:
{ key : "value" ,
list : [
{
key : "values1" ,
list : [
{ key : "value2" , list :[{ key : "simpleValue" } ]
}
]
},
{
key : "value3"
}
]
}
Output:
{key : ["value" , "values1" , "values2" , "simpleeValue", "values3"]}
the code that I wrote for conversion is
var outputArray=new Array();
var count=0;
function recursion(testData){
if(testData.key==undefined)
{
return ;
}
else
{
outputArray[count]=testData.key;
count++;
for(var k in testData.list)
{
testData1=testData.list[k];
recursion(testData1);
recursion(testData.key);
}
}
return outputArray;
}
The output will only give me the value list an array,like [
'value',
'values1',
'value2',
'simpleValue',
'value3'
], how do I use the hash method to get the correct output?
Hmm, something like this??
var inpObj = { key : "value" ,list : [
{
key : "values1"
},
{
key : "value3"
}
]
};
var outputObj = new Object;
var outputArray = new Array();
function recursion(testData){
if(testData.key==undefined)
{
return;
}
else
{
var newKey={};
//alert(testData.key);
outputArray.push(testData.key);
for(var k in testData.list)
{
testData1=testData.list[k];
recursion(testData1);
recursion(testData.key);
}
}
return outputArray;
}
recursion(inpObj);
if (outputObj.key == undefined) outputObj.key = outputArray;
alert(outputObj.key.join(", "));
I got this thing sorted out
var outputArray=new Array();
function recursion(testData){
if(testData.key==undefined)
{
return ;
}
else
{
//alert(testData.key);
outputArray.push(testData.key);
for(var k in testData.list)
{
testData1=testData.list[k];
recursion(testData1);
recursion(testData.key);
}
}
var l={};
l.key=outputArray;
return l;
}

Categories