Adding empty key, value pair to javascript object - javascript

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[""] = "";

Related

Javascript/JSON: get name of specified object as string

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];

What's the difference between this two javascript objects

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.

merge two object and rename same property

I have two object which contain some similar properties. I want to merge those two object in one object and also want to rename the similar properties from both objects.
var selectedEntity = {"UsageS":"123","DateS":"2016","IsEstimeated":"True"};
var ComapareEntity = {"UsageC":"124","DateC":"2015","IsEstimeated":"False"}
Result = {"UsageS":"123","DateS":"2016","IsEstimeatedS":"True","UsageC":"124","DateC":"2015","IsEstimeatedC":"False"};
Please suggest some solution using lodash.
Try to put these two objects in a json array, so that index can used to name duplicate keys
var selectedEntity = {
"UsageS": "123",
"DateS": "2016",
"IsEstimeated": "True"
};
var ComapareEntity = {
"UsageC": "124",
"DateC": "2015",
"IsEstimeated": "False"
}
var toLoopArray = [selectedEntity, ComapareEntity]
var resultantObject = {};
toLoopArray.forEach(function(item, index) {
for (var keys in item) {
if (!(resultantObject.hasOwnProperty(keys))) {
resultantObject[keys] = item[keys]
} else {
resultantObject[keys + index] = item[keys]
}
}
})
console.log(resultantObject)
JSFIDDLE

JS: Convert a specific values from an object into an array?

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)

Searching JavaScript JSON objects

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);

Categories