I have a list of objects like this.
I'm stuck right now, couldn't figure out how to retrieve a value of a an object, by submitting the key
"ListOfObjects": [
{
"SomethingToRetrieve": "This Is The First Value"
},
{
"AnotherThingToRetrieve": "This Is Another Value "
},
{
"LastToRetrieve": "This Is the Last Value"
}
]
I want by creating a function :
retrieveValue(Key){
// by giving as Example AnotherThingToRetrieve
// It will return the Value of this key
//return "This Is Another Value "
}
You could filter all objects that have that key and then return the value from the first matching object. If you leave off the [0] at the end you'll get an array of all matching values.
var listOfObjects = [
{
"SomethingToRetrieve": "This Is The First Value"
},
{
"AnotherThingToRetrieve": "This Is Another Value "
},
{
"LastToRetrieve": "This Is the Last Value"
}
]
const retrieveValue = key => listOfObjects.filter(x => x[key]).map(x => x[key])[0];
console.log(retrieveValue("AnotherThingToRetrieve"))
Use forEach over your json. Object.keys(e) will give you keys inside object literals.
Loop through JSON
Loop through all keys within Object literal {}
Match with key return value if matched.
var ListOfObjects= [{"SomethingToRetrieve": "This Is The First Value"},{"AnotherThingToRetrieve": "This Is Another Value "},{
"LastToRetrieve": "This Is the Last Value"}]
function getVal(key){
ListOfObjects.forEach(function(e){//step #1
Object.keys(e).forEach(function(eachKey){//step #2
if(key == eachKey){//step #3
console.log(e[key]);
return ;
}
})
})
// one liner using find
alert(Object.values(ListOfObjects.find(el=>Object.keys(el).find(ee=>ee==key))))
}
getVal('AnotherThingToRetrieve');
You can also use find The find() method returns the value of the first element in the provided array that satisfies the provided testing function.Inside commented statement under alert.
You have a nested array. You can run a nested for loop to iterate through it until you find a match like so:
var listOfObjects = [
{
"SomethingToRetrieve": "This Is The First Value"
},
{
"AnotherThingToRetrieve": "This Is Another Value "
},
{
"LastToRetrieve": "This Is the Last Value"
}
]
var key = "LastToRetrieve";
console.log(retrieveValue(key));
function retrieveValue(Key){
// by giving as Example AnotherThingToRetrieve
// It will return the Value of this key
//return "This Is Another Value "
var value = "";
for(var obj in listOfObjects) {
for(var item in listOfObjects[obj]) {
if(item === key) {
value = listOfObjects[obj][item];
break;
}
}
}
return value;
}
Related
I have an array of nested objects.
const data = [
{
audi: {
model_Q3: 'Q3',
model_A3: 'A3'
}
},
{
mercedes: {
model_GLA: 'GLA',
model_GLC: 'GLC'
}
}
];
I want a function to return true if the nested object's (audi, mercedes) key or value equals/includes the parameter.
function findCar(parameter) {
let exists = false;
data.forEach(cars => {
Object.entries(cars).map(([_, carValues]) => {
console.log(carValues)
});
});
}
findCar('model_Q3') //true;
findCar('model_') //true;
findCar('GLA') // true;
findCar('GL') // true;
Thanks.
Since you're working with a simple object the JSON.stringify method should come quite handy here. It constructs a json string that contains the entire object, and therefore all the keys and values you have in your object. With that string you can extract every key or value by a regex match.
This is how it may look like:
function findCar(parameter) {
const keysAndValues = JSON.stringify(data).match(/"([^"]+)"/g);
for (let entry of keysAndValues) if (entry.includes(parameter)) return true;
return false;
}
The regex here matches for every entry that starts with ", then only characters that are not " and followed by a ".
Am facing an issue with while filtering array of object using JavaScript filter. Can any one help me to solve this issue.
Here is the code below.
var searchString = "item1";
var data = [
{
checkInfo: {
checkId: "item1"
}
},
{
checkInfo: {
checkId: "item2"
}
}
];
Am trying to filter above data using the below method.
const output = searchString ? data.filter(list => list.checkInfo.checkId === searchString)[0] : data[0];
I want to output if matched i want return matched object. If not matched always want to return first array of object from data array. It's working fine for match case. When searchString word not matching the ternary else condition not executing and it's returning undefined. Can any one look into my code and give your suggestion.
You are currently checking if searchString is defined and making the choice based on that. If you want to check if something matched with the filter you need to run the filter first and then check. Since it looks like you are only searching for the first match, you could just use find()
The following will check both:
var searchString = "item14";
var data = [{
checkInfo: {
checkId: "item1"
}
},
{
checkInfo: {
checkId: "item2"
}
}
];
let match = data.find(list => list.checkInfo.checkId === searchString)
const output = (searchString && match) || data[0];
console.log(output)
The filter functions returns an empty array if nothing is found, which is a truth-y value, so the ternary condition never triggers the false condition.
Thus, the first entry in an empty array is undefined.
Using the filter we can do this way
var searchString = "item3";
var data = [
{
checkInfo: {
checkId: "item1"
}
},
{
checkInfo: {
checkId: "item2"
}
}
];
var temp = data.filter(item => (item.checkInfo.checkId === searchString));
temp = temp.length > 0 ? temp : data[0];
console.log(temp);
When you call the .find(callback) method on an array, you will get back the first item that matches the condition that you specify. If no items are found, you will get back undefined.
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I have following json
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
I can access for instance the second element of the array like this:
dictionary[1].value
it returns 10 which is the score of the History subject.
What I'm looking for is the way so that I can access it by the word "History" itself, I mean I need a code like this:
dictionary["History"].value
How can I achieve that?
Ok, so here is a hack. You can use Array as an Object and insert any key you want. You can apply forEach to it and bind keys with properties like below.
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
dictionary.forEach(function(item) {
dictionary[item.key] = item;
});
console.log(dictionary["History"].value);
Note: This is just a Hack and will fail in case of duplicate entries.
Edited
Solution in case of duplicate keys
var dictionary = [{
"key": "Math",
"value": "20"
}, {
"key": "History",
"value": "10"
}, {
"key": "Chemistry",
"value": "12"
}, {
"key": "Chemistry",
"value": "13"
}]
dictionary.forEach(function(item) {
if (dictionary[item.key] && !Array.isArray(dictionary[item.key])) {
dictionary[item.key] = [dictionary[item.key]];
dictionary[item.key].push(item);
} else if (dictionary[item.key] && Array.isArray(dictionary[item.key])) {
dictionary[item.key].push(item);
} else {
dictionary[item.key] = item;
}
});
console.log(dictionary["Chemistry"]);
By using find() to iterate over your array.
From MDN Array.prototype.find():
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
const dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
const result = dictionary.find(item => {
// if this returns `true` then the currently
// iterated item is the one found
return item.key === 'History'
})
console.log(result)
There's more than one way to do this but this one is the most straightforward and succinct.
Try this:
var dictionary = [
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
];
function getValue(searchKey) {
var retVal;
dictionary.some(item => {
if (item.key === searchKey) {
retVal = item.value;
return true;
}
});
return retVal;
}
console.log(getValue('History'));
If goes through your array of objects and finds the object that matches its key to your searchKey and returns the result.
Or you can convert your array of objects into a single object and then reference it directly:
var dictionary = {};
[
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
].forEach(item => {dictionary[item.key] = item.value;});
console.log(dictionary.History);
I'm converting an xml string to json using php and then posting it to a
javascript file where I try to iterate it. When the object contains more than one object, json contains an array of objects like the first sample and I can iterate using the .length function but when the object contains only 1 object an array is not being created and the .length function fails. How can I make the iteration work in both cases without knowing the object's name?
Sample 1:
{"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
Sample 2:
{"class":
{
"name":"history",
"grade":"10"
}
}
You could check length, and if it's undefined it means it's just an object, then you make it an array with just one element:
if collection.length == undefined:
collection = [collection]
# the rest of the code doesn't need to be changed
You can use for for that and you don't need length
var test = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
for (var i in test){
console.log(test[i]);
}
You can check to see if the object is an array first: Array.isArray(obj) . If it isn't then you know you don't need to iterate it.
var obj = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
if (!Array.isArray(obj)) return obj;
// else iterate it.
You have to know the data type of the variable before knowing how to use .length properly.
var dataTypeLength;
var data = {
"class":
{
"name":"history",
"grade":"10"
}
}
if (Array.isArray(data.class)) {
dataTypeLength = data.class.length;
} else {
dataTypeLength = Object.keys(data.class).length;
}
console.log(dataTypeLength);
I have a json, it is
{
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
}
I want to recovery the structure, like
{
"prop1": {
"sub1": {
"sub2" : "content1",
"sub3" : "content2"
}
},
"prop2": {
"sub1": {
"sub2" : "content3"
}
},
"prop3": {
"sub1": {
"sub2" : "content4"
}
}
}
I split the key with dot to get each key.
for (var key in json) {
var keySplit = key.split('.');
// Todo: recovery the structure
}
But not found a good solution.
Is anyone has solution?
You can use Array#reduce method.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
};
// iterate over the property names
Object.keys(obj).forEach(function(k) {
// slip the property value based on `.`
var prop = k.split('.');
// get the last value fom array
var last = prop.pop();
// iterate over the remaining array value
// and define the object if not already defined
prop.reduce(function(o, key) {
// define the object if not defined and return
return o[key] = o[key] || {};
// set initial value as object
// and set the property value
}, obj)[last] = obj[k];
// delete the original property from object
delete obj[k];
});
console.log(obj);
Answer by Pranav C Balan is right for the question you asked. But JSON's might not be as simple as you have mentioned above and can have array's also and few keys might not have "." in them. To handle all these cases you can use the following one.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.0.sub2": "content4"
};
function createJSONStructure(obj) {
Object.keys(obj).forEach(function(k) {
var prop = k.split('.'); //split on . to get elements
if(prop.length >1){ //If there is no dot just key the value as is.
let data = obj;//Copy the default object to data in each loop
for(i=0;i<prop.length-1;i++){
if(data[prop[i]]){ // Check if the key exists
if((prop[i+1].match(/^\d+$/) && !Array.isArray(data[prop[i]])) // Check if the next key is a digit and the object we have is a JSON
|| (!prop[i+1].match(/^\d+$/) && Array.isArray(data[prop[i]]))){ // Check if the next key is not a digit and the object we have is a Array
throw new Error("Invalid header data"); //If any of the above cases satisfy we cannot add the key so we can throw an error.
}
data = data[prop[i]]; // If key exisits make the data variable as the value of the key
}else {
if(prop[i+1].match(/^\d+$/)){ //If the key is not available see if the next parameter is a digit or string to decide if its array or string
data[prop[i]] = [];
}else{
data[prop[i]] = {};
}
data = data[prop[i]]; //Assign this new object to data
}
};
data[prop[i]] = obj[k]; //Finally add the value to final key
delete obj[k]; // delete the exisiting key value
}
});
return obj;
}
console.log(createJSONStructure(obj));