I am trying to get values from the following object. The for loop works in one of the objects but won't in the other javascript object. I was wondering what the difference and how can I get it to work in the other object?
Object 1:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
}
];
Object 2:
{
"4dd5a49e366": {
"name" : "bar",
"bar" : "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name" : "lorem",
"bar" : "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}
I want to do a search for items where name attribute is matching some search_term. And return the items.
Here is the search for loops am using.
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var i in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('o'));
This works for the first object and not for the second. How can I get it to work for the second?
The first variable is an array of objects. Since it is an array you can use all array methods on it.
Second one is an object with keys 4dd5a49e366 & 519c5056af2 which in turn are again object and have few properties.
You cannot use array methods on this second object
how can I get it to work in the other object?
Hope this snippet will be useful
var myObject = {
"4dd5a49e366": {
"name": "bar",
"bar": "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name": "lorem",
"bar": "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}
// a function to accept the name value
function findByName(name) {
var thisObject = "";
for (var keys in myObject) { // looping over objects
var getThisObject = myObject[keys];
if (getThisObject.name === name) { // Checking if name matches
thisObject = myObject[keys]; // assigning the object to a variable
}
}
return thisObject // return that variable
}
var getMyObject = findByName('bar');
console.log(getMyObject)
JSFIDDLE
EDIT
if I enter just findByName('b'); it should return results that the
full name
You need to use indexOf to find if this name value contains the specific character.
Use an array to store all the relevant object where the name value contains this specific character.Return that array from the function.
function findByName(name) {
var thisObject = [];
for (var keys in myObject) {
var getThisObject = myObject[keys];
if (getThisObject.name.indexOf(name)!==-1) {
thisObject.push(myObject[keys]);
}
}
return thisObject
}
var getMyObject = findByName('b');
JSFIDDLE 2
I suggest you do some reading on JavaScript Object literals and Arrays. The first example is an array of objects. The second is just an object. Two completely different data structures.
Related
How can I add empty (key,value) pair to an existing object.
suppose I have an object as
var map = {
"name": "x"
};
How can I get below output
var map = {
"name": "x",
"": ""
};
I am looking for similar to push function in case of array.
You just need to use the [] operator, like that :
var map = {
"name": "x"
};
map[""] = "";
I'd like to get a key name of a JSON/JavaScript object as string. Maybe this is totally easy, but i just can't figure it out.
I have this object (simplified example, there are reasons to name the keys as strings):
var obj = {
"input1": {
"type": "input",
"value": "aaa"
},
"input2": {
"type": "checkbox",
"value": "bbb"
}
}
And now i would like to do something like this:
currentInputName = getTheNameOfThisAsString(obj.input1);
console.log(currentInputName); // output should be "input1"
currentInputName = getTheNameOfThisAsString(obj.input2);
console.log(currentInputName); // now output should be "input2"
I'm trying this with Object.keys() and Object.getOwnPropertyNames(), but both return type and value to me, so they are outputting the keys of the object specified, not the object name itself.
Use Object.keys() to access keys of your object.
var obj = { "input1": { "type": "input", "value": "aaa" }, "input2": { "type": "checkbox", "value": "bbb" } };
var keys = Object.keys(obj);
console.log(keys);
I am not sure what you are trying to accomplish, but I assume that you do not know the key, and thus you are sending object.key to your method.
How about changing the method to take the object and your object.key as parameters?
You call your method like this: getTheNameOfThisAsString(obj, obj.input1);
function getTheNameOfThisAsString(obj, subObject){
var keys = Object.keys(obj);
for(var key in keys){
if(subObject.value == obj[key].value){
return key;
}
}
}
From your comments, I was wondering if you can store your sub-object like this: currItem=obj["input1"], if that is the case, you already have the key as a string, and there is no need for an explicit method.
Here is an example:
var currItemName = "input1";
var currItem=obj[currItemName];
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 have an object:
var obj =
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]
And I want to convert the values of the labels ONLY into an array so that the end result is:
["AEP", "CAP", "CASL"]
How do I only get the label values converted in an array?
First: obj is not an object, it is an array since the parent brackets are [] and not {}. I will, however, keep the name the same. This might have caused you some confusion, e.g.
var object = {};
var array = [];
var arrayOfObjects = [{},{},{}];
var objectOfArrays = {array1: [],array2: [],array3: []};
To loop an array you can use a for loop:
// new array
var newArray = [];
// iterates over each index in the array
for(var i=0; i<obj.length; i++) {
// Access the specific index, then access its `label` property
// Push into `newArray`
newArray.push(obj[i].label);
}
console.log(newArray);
Codepen: http://codepen.io/theblindprophet/pen/RRxVba
Using a for loop
var out = [];
for (var i = 0, len = obj.length; i < len; i++) {
out.push(obj[i].label);
}
console.log(out);
Its simple. You can use map function of javascript array
var obj =
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]
var arr = obj.map(function(data){return data.value});
This is a functional solution and not the most straightforward one, you may want to refer to #theblindprophet's answer for the imperative approach to this problem.
Pretty easy task to be done in a functional way:
var labels = obj.map(function(inner) { return inner.label });
How does one approach such a problem: You need to think of how to transform the data you have to the data you want. In this case you have an Array of Objects and you want to transform this Array of Objects to an Array of Strings placed inside that Object.
The above code iterates over the Array and returns the value you want for the current element of the Array, building a new Array in the course (map)
My PHP is returning the following JSON (2 entries shown, it could be more, but the structure will be the same):
{
"0": {
"campaign_id": "31",
"title": "new title",
"description": "new description",
"destinations": {}
},
"1": {
"campaign_id": "32",
"title": "title",
"description": "description",
"destinations": {}
}
}
I want to access the destinations where campaign_id matches a given value. How do I do that?
Using lodash.find:
var data = ...
var destinations = _.find(data, e => e.campaign_id == 31).destinations;
Pure JS
function find(data, predicate, def) {
for (var key in data) {
if (data.hasOwnProperty(key) && predicate(data[key], key)) {
return data[key];
}
}
return def;
}
var data = ...
var destinations = find(data, e => e.campaign_id== 31).destinations;
The best solution with dictionaries
In this case it would be the best if the server would actually send an object, where the items themselves are keyed by their campaign_id, then it would be just:
var data = ...
data[31].destinations
You can use Object.keys and the filter to perform matching:
Object.keys() returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop.
Array.prototype.filter() creates a new array with all elements that pass the test implemented by the provided function.
Array.prototype.map() creates a new array with the results of calling a provided function on every element in this array.
var obj = {...}; //your data object
var destinations = Object.keys(obj).filter(function(key) {
return obj[key].campaign_id === "32"
}).map(function(key) {
return obj[key].destinations;
});
Transform your response to object:
var obj = JSON.parse(response);
Now you can loop through the JSON:
var destinations;
for (var key in obj) {
if (obj[key].campaign_id == "value") {
destinations = obj[key].destinations;
break;
}
}
console.log(destinations);