Efficient way to find name value pairs from JSON array in Javascript - javascript

I am currently making a call to a service which sends a response as an array of objects with name value pairs. An example of this can be seen below. There could be any amount of these name value pairs in any order but I just want to access the value for the name "name2". Is there an efficient way other than looping through each object and checking the name to obtain the corresponding value for name2?
[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}]
So from the above data set I would want an efficient way to search for name2 and get the corresponding value "value2".
Thanks

Unless you know the specific index of the object with the name name2 no.
You'll need to iterate until you find that name then you can bail out.
e.g.
var jsonData = [{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}];
for(var i=0;i<jsonData.length;i++){
if(jsonData[i]['name'] == 'name2'){
console.log('The value is: ' + jsonData[i]['value']);
break;
}
}
Note that if you don't need to support Internet Explorer, you can use the Array.find() method to simplify this.

if you don't want to iterate over the array manually you can use lambda expression as the following
a =[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}] ;
//get the items that match your criteria
a.filter(item=>item.name=="name2")
//get those items' values
a.filter(item=>item.name=="name2").map(item=>item.value)
//get the first value (if you know that it's only one item that will match)
a.filter(item=>item.name=="name2").map(item=>item.value)[0]

You can use Array#find method.
var arr = [{
"name": "name1",
"value": "value1"
}, {
"name": "name2",
"value": "value2"
}];
// get the object containing name as `name2`
var obj = arr.find(function(v) {
return v.name === 'name2';
});
// get value property if object is defined
var res = obj && obj.value;
console.log(res)

Related

React - convert object into array of objects with properties

I have the following object
"data":{
"name 1":"a",
"name 2":"b",
"name 3":"b",
},
How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render compoents for each one passing in the both the name and data?
If you use a reduce function you can do the following to achieve your goal
Object.keys(data).reduce((array, key) => {
return [...array, {key: data[key]}]
}, [])
Reduce is a cool function that iterates and combine data into one single item (could be 1 object, array, integer, etc).
Object.keys() is a way to get each key from the current object and be able to iterate over each.
The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
so you can try something like this
let result = Object.entries(data);
result.map((item, index)=>{
console.log('key is:- ', item[0], ' and value is:- ', item[1]);
});
you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.
This will convert to array of objects that will keep both the name and data.
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
}
var res = Object.keys(data).map(function(name){
var obj = {};
obj[name] = data[name];
return obj;
});
console.log(res);
js native method u can use;
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
};
var newObj = [...Object.values(data), ...Object.keys(data)]
console.log(newObj)

Accessing a JSON key based on a lower level property in Javascript [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I'm pretty sure this has been asked before, but I can't seem to find the solution, for lacking the appropriate words to describe the issue.
I'm trying to access an object's key (e.g. "ID1"), in an object of objects, according to the value of one of its lower keys (e.g. "name":"name1").
The JSON object contains different ID objects, each of which contains a name and other properties.
mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
It's pretty simple to get the name if I know the ID, e.g.:
myname = mydata["ID1"].name; //returns "name1"
But what I'm trying to do is get the ID of an object if I know its name, so in short, the reverse of the above line. Is there any simple solution for this (in pure Javascript or jQuery)? Note: I know the names are unique.
If I'm understanding you correctly, Object.keys() can help you. It would look something like this:
var mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
Object.keys(mydata).forEach(function(id) {
var obj = mydata[id];
if (obj.name === "name1") {
// I found an object based on the "name" property.
// the 'id' variable holds a reference to it.
}
});
var mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
var parentId = Object.keys(mydata).find(function(key){
return mydata[key].name === 'name2';
});
console.log(parentId);
The only way to do it, is to traverse over every property-value.
var result = null;
for(var key in mydata) {
if(mydata[key].name==='name1'){
result = key;
break;
}
}
console.log(result);

JavaScript - Check if a particular key is available in the JSON

I am retrieving JSON from a live streaming data.
For the first call I am getting dataset array with time and value. But in the second JSON dataset array is empty. I want to check if dataset array contains time key.
Retrieved JSON after first call:
{
"activities-heart-intraday": {
"dataset": [{
"time": "00:00:00",
"value": 91
}, {
"time": "00:01:00",
"value": 92
}, {
"time": "00:02:00",
"value": 92
}],
"datasetInterval": 1,
"datasetType": "second"
}
}
Retrieved JSON after second call:
{
"activities-heart-intraday": {
"dataset": [],
"datasetInterval": 1,
"datasetType": "second"
}
}
I am doing
var value = JSON.parse(data);
if (value.hasOwnProperty('time')) {
console.log("here");
}
to check if time key exists in the JSON, but it's not working.
How can I check if a particular key exists in the array in json?
Firstly you have to check that dataset is not an empty array. Then check that time is defined.
This can be solved with:
if (dataset[0] !== undefined && dataset[0].time !== undefined)
or just:
if (dataset[0] && dataset[0].time)
If you want to iterate through the array:
dataset.forEach(function (data) {
if (data.time) {
// your code
}
});
the data has a dataset array so we need to first check if the array is there and then if one of the arrays members has the time property
if( data.hasOwnProperty('dataset') && data.dataset.length != 0){
if( data.dataset[0].hasOwnProperty('time')){
console.log('true');
}
}
Since in JS you can not natively set and access object properties those with a "-" character in it by dot notation you have define them as strings and use bracket notation instead to set and access them. So you can make a check like this
data["activities-heart-intraday"].dataset.length > 0 && data["activities-heart-intraday"].dataset.every(e => !!e.time);
I can't really tell what data from your question is supposed to be but if it is the whole JSON object, then the most simple way is this:
if(data["activities-heart-intraday"]["dataset"][0]["time"])
console.log('time is set)
But beware! If for example the dataset is not set, you'll get an error that you are trying to get time key from undefined and the code will crash. I'd recommend using simple recursive function like this:
function is_there_the_key(json, keys){
if(keys.length == 0)
return true //we used the whole array, and every key was found
let key = keys.shift() //pop(get and remove) the first string from keys
if(!json[key]){
console.log(key + ' not found')
return false //one of the keys doesn't exist there
}
return is_there_the_key(json[key], keys)
}
Whether you return true or false, both of them will make their way up to the surface.
As the json parameter you pass the json you want to search in.
As the keys parameter you pass an array (mostly strings) of the keys in order they should go.
For example:
if(is_there_the_key(data, ["activities-heart-intraday", "dataset", 0, "time"])
//we found the key, do something here

How to add an element containing fields to an array

Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:
shopsArray[4].shopName
Edit:
It's working with Pointy's answer but I still have a problem:
shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );
The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.
Can you see what's the problem here?
Edit 2:
More elaborate code:
// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();
// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
shopsArray[i].shopName = $('#secondaryName' + i).val();
shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}
// save new branches to array
for (var j=1; j<=newshopsCounter; j++){
var bName = $('#newName' + j).val();
shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});
alert(bName);
alert(shopArray[1].shopName);
alert(shopsArray[1].shopId);
}
The first and third alerts give the correct values. The second one gives undefined.
You mean something like
shopsArray.push({ shopName: "Fred", value: "Ethel" });
?
edit — now that I know that this is the sort of thing you want to do, I'll clarify.
JavaScript has an "object literal" syntax that allows objects to be created directly as values. The syntax involves a list of property names and values, with the names and values separated by a colon and each pair separated by commas. Thus:
var anObject = { someProperty: "the value" };
creates an object with one property and assigns it to the variable "anObject". That's effectively the same as:
var temp = new Object();
temp["someProperty"] = "the value";
var anObject = temp;
The "value" part of a property in an object literal can be any expression, but the property name must be either a string constant or an identifier (and in either case, it's treated like a string constant). Thus, you can create an object with a property whose value comes from calling some function:
var fancyObject = { "temperature": getTemperature() };
Object literal expressions are values, and can be used anywhere you can use an expression, including function call arguments. Therefore, to add an object to an array, it's possible to call the array ".push()" function and use an object literal as the argument, as in the first example:
shopsArray.push({ shopName: "Cheese Shoppe", shopPhone: "111 222 3232" });
You can even include object literals inside another object literal, as the value of a property:
shopsArray.push({
shopName: "Cheese Shoppe",
shopAddress: {
street1: "207 High Street",
street2: "No. 5",
city: "Austin",
state: "TX"
}
});
You would simply create a hash inside an array to achieve that:
var shopsArray = [
{
shopName: 'value1'
}, {
shopName: 'value2'
}
];
If you have an existing array, use push:
shopsArray.push({ shopName: 'value' });
you can do something like this:
var arr = new Array();
arr['field_name'] = 'field_value';
//to access it on ajax
for (var i in arr){
//field_name is in "i"
//field_value is in arr[i]
}

Handling JSON Object Array

I got a realy simple question:
Take a look at this JSON String:
this.objects = [{"pid":"2","x":"10","y":"10"}]; // only one i know
Now i would like to adress an object out of it like so:
this.objects.pid[2]
I know thats pointless in this case as you would access it like:
this.objects[0]
The thing is that i need to adress an object array in JSON by the object id and not the array index. Is there a nice approach to this?
Thanks!
function getObject(id, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].pid == id) {
return array[i]
}
}
}
A function that takes your id and array and returns your object. Basically loop through the array and find the element with your id. This can be optionally cached for speed increase.
It doesn't need to be a single element array, so try this...
this.objects = {"pid":"2", "x":"10", "y":"10"};
And you can read it either of these ways:
this.objects.pid;
this.objects['pid'];
If you wanted multiple lists of x,y,etc. then try something like this:
this.objects = { "2": {"x": "10", "y": "10"} };
this.objects["2"].x;
this.objects["2"]["x"];
Essentially, in this case, just use the "pid" as they key for each object that contains the properties you want for each item.

Categories