Output value from Json Array - javascript

I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.

EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.

var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}

Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;

Related

Acessing an object propery with array bracket notation

I want to access a specific property in an object. Using an array for example
let array = ["tom","tony", "jerry"];
let object = {
tony: "Brother",
tom: "Uncle",
jerry: "Cousin",
};
object.array[1];
I'm trying to access object.tony but what happens is that it returns object."tony" instead.
The problem is that it returns it as a string so it causes an error.
Is it possible to return array[1] not as a string?
In object.array[1], JS will think your looking for array inside object, which does not exist. If an array was in the object, it would work:
let object = {
array: ["tom", "tony", "jerry"],
// some other stuff...
};
console.log(object.array[1]);
You can use brackets instead:
object[array[1]];
Example:
let array = ["tom","tony", "jerry"];
let object = { tony: "Brother", tom: "Uncle", jerry: "Cousin", };
console.log(object[array[1]]);

convert json values in comma separated string using javascript

I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);

Grabbing names of object of out a JSON object in javascript and storing it in an String Array

So the issues that I am currently having is a string manipulation logic issue. My goal is to store the names of JSON objects in a string array. So it will be easier to access the data later on. But the current issue that I am running into is that the output is nothing that I want or understand of how it is getting it. Currently I am looking for the quotes between the object names and returning it to a string using str.substring, and storing it in an index of newArr. The output equals in 4th code snippet. I have also tried putting an underscore before and after the object name in the JSON object, then searching for the underscore. From my testing this will only work with the first name, which will return "foo" in index 0, while the rest of the indexes equal to '"_'. I know there is something wrong with my logic in the function, but I can not pinpoint what it is. Any help would be appreciated
This is the function that is being ran.
exports.jsonObjectToArray = function (objectToTurn){
var oldArr = JSON.stringify(objectToTurn).split(","),
firstIndex,
secondIndex,
newArr = [];
for(let i = 0; i < oldArr.length; i ++){
firstIndex = oldArr[i].indexOf("\"");
secondIndex = oldArr[i].indexOf(firstIndex, "\"");
newArr[i] = oldArr[i].substring(firstIndex, secondIndex);
}
return newArr;
}
When the function is ran oldArr will equal to this value.
[ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
And my goal is to return this. Which will be stored in newArr.
[
"foo",
"bar",
"Mar",
"Car"
]
But after the function runs this is what I get returned.
[
'{"',
'bar":"0',
'Mar":"0',
'Car":"0'
]
To get the keys from an object, simply use Object.keys().
Quick example:
var obj = {
foo: '1',
bar: '2',
car: '3'
};
console.log(Object.keys(obj)); // ==> (3) ["foo", "bar", "car"]
let arr = [ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
let arr1 = arr.map(el => el.split('"')[1])

java script to transform json data

my survey output is like
{"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"} when it reaches the jsp, and i would like to change 0 to good, 1 to bad and 2 to ok, which are the outputs of a,b,c,d .how can we do it using foreach function.
Something like this?
var input = {"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"};
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var newObject = Object.keys(input).reduce(function(previous, current) {
previous[current] = mapvals[input[current]] || input[current];
return previous;
}, {});
console.log(newObject);
Which gives:
{
a: "bad",
b: "ok",
c: "bad",
d: "good",
e: "please improve",
Id: "789"
}
You could do it manually with a forEach function if you really wanted... but I'll leave that to you.
foreach() and map() only work on arrays, so they can't be used directly on your object. You'll have to use the keys() or entries() functions first to get the fields in the object as an array.
Unfortunately Object.entries() currently only works in Firefox(*). However, as it happens, keys() produces simpler code anyway.
var input = {"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"};
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var output = {};
Object.keys(input).forEach(function(key) {
output[key] = mapvals[input[key]] || input[key];
});
console.log(output);
(*) It's available in Chrome also, but only behind a configuration flag.
you could convert the values when serializing the object. Before you send the json to the backend:
var data = {"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"};
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var json = JSON.stringify(data, (key, value) => key && value in mapvals? mapvals[value]: value);
json:
{"a":"bad","b":"ok","c":"bad","d":"good","e":"please improve","Id":"789"}
you can also add further "filter" to only apply this logic to some keys
also works with more complex data, like the Array of items like that, that you mentioned.
var data = [
{"a":"0","b":"2","c":"0","d":"0","e":" ","id":"456"},
{"a":"0","b":"0","c":"0","d":"0","e":"test","i‌​d":"123"},{"a":"0","‌​b":"2","c":"0","d":"‌​0","e":"please test ","id":"456"},
{"a":"0","b":"2","c":"0","d":"0","e":" ","id":"456"},
{"a":"0","b":"1","c":"1","d":"0","e":" ","id":"456"},
{"a":"2","b":"2","c":"2","d":"2","e":" ","id":"789"},
{"a":"1","b":"1","c":"1","d":"1","e":"survey ","id":"789"},
{"a":"1","b":"1","c":"2","d":"2","e":"1234567"‌​,"id":"789"},
{"a":"0‌​","b":"0","c":"0","d‌​":"0","e":" ","id":"234"}
];
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var json = JSON.stringify(data, (key, value) => key && value in mapvals? mapvals[value]: value);
json:
[{"a":"good","b":"ok","c":"good","d":"good","e":" ","id":"456"},{"a":"good","b":"good","c":"good","d":"good","e":"test","id":"123"},{"a":"good","b":"ok","c":"good","d":"good","e":"please test ","id":"456"},{"a":"good","b":"ok","c":"good","d":"good","e":" ","id":"456"},{"a":"good","b":"bad","c":"bad","d":"good","e":" ","id":"456"},{"a":"ok","b":"ok","c":"ok","d":"ok","e":" ","id":"789"},{"a":"bad","b":"bad","c":"bad","d":"bad","e":"survey ","id":"789"},{"a":"bad","b":"bad","c":"ok","d":"ok","e":"1234567","id":"789"},{"a":"good","b":"good","c":"good","d":"good","e":" ","id":"234"}]

Uncaught TypeError: data.push is not a function

I am trying to push
data.push({"country": "IN"});
as new id and value to a json string. but it gives the following error
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
Advance Thanks for your reply
To use the push function of an Array your var needs to be an Array.
Change data{"name":"ananta","age":"15"} to following:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
The containing Array Items will be typeof Object and you can do following:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.
Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
So you can iterate and always can get the properties, even if they are empty, null or undefined.
edit
Cool stuff to know:
var array = new Array();
is similar to:
var array = [];
Also:
var object = new Object();
is similar to:
var object = {};
You also can combine them:
var objectArray = [{}, {}, {}];
Your data variable contains an object, not an array, and objects do not have the push function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
Also make sure that the name of the variable is not some kind of a language keyword.
For instance, the following produces the same type of error:
var history = [];
history.push("what a mess");
replacing it for:
var history123 = [];
history123.push("pray for a better language");
works as expected.
you can use push method only if the object is an array:
var data = new Array();
data.push({"country": "IN"}).
OR
data['country'] = "IN"
if it's just an object you can use
data.country = "IN";
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('') will not work as it is not an array anymore.
One things to remember push work only with array[] not object{}.
If you want to add object o inside inside n like that :
a = {
b:"c",
D:"e",
F: {
g:"h",
I:"j",
k: {
l:"m"
}
}
}
a.F.k.n = { o: "p" };
console.log(a);
Try This Code $scope.DSRListGrid.data = data; this one for source data
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
make sure you push into an Array only
and if their is error like Uncaught TypeError: data.push is not a function**
then check for type of data
you can do this by consol.log(data)
hope this will help
let dataArray = [{'id':1,'code':'ABC'},{'id':1,'code':'ABC'},{'id':2,'code':'ABC'}]
let obj = {};
dataArray.forEach(task => {
task.id in obj ? obj[task.employee_id].push(task):
obj = {
...obj,
[task.employee_id]: [task],
}
});

Categories

Resources