AmazingDayToday
AmazingDayToday

Reputation: 4272

Javascript: Find key and its value in JSON

I have a JSON object that is returned in different ways, but always has key. How can I get it?

E.g.

"Records": {
    "key": "112"
}

Or

"Records": { 
    "test": {
        "key": "512"
    }
}

Or even in array:

"Records": { 
    "test": {
        "test2": [
            {
                "key": "334"
            }
        ]
    }
}

Tried several options, but still can't figure out (

Upvotes: 4

Views: 49721

Answers (5)

Tan
Tan

Reputation: 352

You can try this

const data = {
	"Records": {
		"key": "112"
	}
};

const data2 = {
	"Records": {
		"test": { "key": "512" }
	}
};

const data3 = {
	"Records": {
		"test": {
			"test2": [
				{ "key": "334" },
			]
		}
	}
};

function searchKey(obj, key = 'key') {
	return Object.keys(obj).reduce((finalObj, objKey) => {
		if (objKey !== key) {
			return searchKey(obj[objKey]);
		} else {
			return finalObj = obj[objKey];
		}

	}, [])
}

const result = searchKey(data);
const result2 = searchKey(data2);
const result3 = searchKey(data3);
console.log(result);
console.log(result2);
console.log(result3);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could use an iterative and recursive approach for getting the object with key in it.

function getKeyReference(object) {
    function f(o) {
        if (!o || typeof o !== 'object') {
            return;
        }
        if ('key' in o) {
            reference = o;
            return true;
        }
        Object.keys(o).some(function (k) {
            return f(o[k]);
        });
    }

    var reference;
    f(object);
    return reference;
}

var o1 = { Records: { key: "112" } },
    o2 = { Records: { test: { key: "512" } } },
    o3 = { Records: { test: { test2: [{ key: "334" }] } } };

console.log(getKeyReference(o1));
console.log(getKeyReference(o2));
console.log(getKeyReference(o3));

Upvotes: 0

Shobhit Walia
Shobhit Walia

Reputation: 496

I will not write the code for you but give you an idea may be it will help, First convert JSON object in to string using

JSON.stringify(obj);

after that search for Key using indexOf() method. Extract previous '{' and Next '}' string and again cast in to JSON object. using

var obj =  JSON.parse(string);

Then

 var value = obj.key

Upvotes: 3

Ruslan
Ruslan

Reputation: 10147

How can i get it?

Recursively! e.g.

function getKey(rec) {
    if (rec.key) return rec.key;

    return getKey(rec[Object.keys(rec)[0]]);
}

https://jsfiddle.net/su42h2et/

Upvotes: 0

Maciej Kozieja
Maciej Kozieja

Reputation: 1865

I think this migth be solution (asuming key is always string and you don't care about res of data)

const data = [`"Records": { 
    "test": {
        "test2": [
            {
                "key": "334",
				"key": "3343"
            }
        ]
    }
}`, `"Records": { 
    "test": {
        "key": "512"
    }
}`, `"Records": {
    "key": "112"
}`]

const getKeys = data => {
  const keys = []
  const regex = /"key"\s*:\s*"(.*)"/g
  let temp
  while(temp = regex.exec(data)){
    keys.push(temp[1])
  }
  return keys
}

for(let json of data){
  console.log(getKeys(json))
}

Upvotes: 1

Related Questions