javascript filter an object - javascript

i have the following Javascript object.
var data =
{
"type": [
"car",
"bike"
],
"wheels": [
"4",
"2"
],
"open": [
"Jan",
"Jan"
],
"wheel_press": [
"35",
"19"
],
"max-weight": [
"4000",
"8"
],
"transition_plan": [
"",
null
],
"number_of_occurence": [
5696,
976
],
"model": [
"sedan",
"street"
}
I want to filter on any of the object key to get only the corresponding values for that key.
so far after searching stackoverflow still not able to find similiar question.
I have tried using
data.filter(type ==='car')
and the error i am getting is
.filter is not a function
the expected output is
if i filter on type === 'car'
then it should only show
{
"type": [
"car"
],
"wheels": [
"4"
],
"open": [
"Jan"
],
"wheel_press": [
"35"
],
"max-weight": [
"4000"
],
"transition_plan": [
""
],
"number_of_occurence": [
5696
],
"model": [
"sedan"
}

You can write a function that finds the index of the value inside the given property and then uses Object.fromEntries(), Object.keys() and Array.map() to create a new object as followings
var data={type:["car","bike"],wheels:["4","2"],open:["Jan","Jan"],wheel_press:["35","19"],"max-weight":["4000","8"],transition_plan:["",null],number_of_occurence:[5696,976],model:["sedan","street"]};
const getFilteredObject = (property, value) => {
const index = data[property].indexOf(value)
return Object.fromEntries(Object.keys(data).map(key => ([key, data[key][index]])))
}
const filteredObject = getFilteredObject('type','car');
console.log(filteredObject)

Related

Load nested object on an array dynamically with javascript

I have a json data in this format and I would like to load data in an array which is an object, without hard coding the object keys. I would like to get items and labels in each category and each category has it name for object key. At the moment I get the data by
...myData.labels.name; or ...items.name; which is not effective because
the name changes depending on the category.
[
[
{
"key": "mykey",
"category": "myCategoryKey",
"category_label": "myCategoryLabel",
"field": "filter",
"items": {
"name": [
"item1",
"item2"
]
},
"labels": {
"name": [
"Item1",
"Item2"
]
}
},
{
"key": "mykey2",
"category": "myCategoryKey2",
"category_label": "myCategoryLabel2",
"field": "filter",
"items": {
"name2": [
"item1",
"item2"
]
},
"labels": {
"name3": [
"Item1",
"Item2"
]
}
}
]
]
Use Object.keys() to get Keys for items present if values change dynamically.
And then use the keys to get corresponding values.
var data = {
"key": "mykey2",
"category": "myCategoryKey2",
"category_label": "myCategoryLabel2",
"field": "filter",
"items": {
"name2": [
"item1",
"item2"
]
},
"labels": {
"name3": [
"Item1",
"Item2"
]
} }
var labelsPresent = Object.keys(data.labels);
console.log(labelsPresent);
var labelValues= labelsPresent[0];
console.log(data.labels[labelValues]);

How to convert array of objects to object with index?

I have a array like this->
var jsonResponse = [
{
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
{
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
And I want to convert it to ->
{
"abc" : {
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
"ccc": {
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?
let indexedResult = {};
jsonResponse.map(obj => indexedResult[obj.name] = obj)
console.log(JSON.stringify(indexedResult));

How to convert string to number in a nested array?

I have the following array of objects which has an array inside an
array. the values are in the string, I want it to be a number. What is
the best possible solution to do that in JavaScript.
[
{
"key": "America",
"values": [
[
"1469664000000",
"1"
],
[
"1469750400000",
"13"
],
[
"1469836800000",
"2"
],
[
"1469923200000",
"1"
],
[
"1470009600000",
"1"
],
[
"1470096000000",
"1"
]
]
},
{
"key": "India",
"values": [
[
"1469750400000",
"1"
]
]
},
{
"key": "China",
"values": [
[
"1469664000000",
"2"
],
[
"1469836800000",
"1"
],
[
"1470096000000",
"12"
]
]
},
{
"key": "Africa",
"values": [
[
"1470096000000",
"1"
]
]
},
{
"key": "UK",
"values": [
[
"1469664000000",
"3"
],
[
"1469750400000",
"3"
],
[
"1469836800000",
"1"
],
[
"1469923200000",
"2"
],
[
"1470009600000",
"4"
],
[
"1470096000000",
"2"
]
]
}
]
var data = [{"key":"America","values":[["1469664000000","1"],["1469750400000","13"],["1469836800000","2"],["1469923200000","1"],["1470009600000","1"],["1470096000000","1"]]},{"key":"India","values":[["1469750400000","1"]]},{"key":"China","values":[["1469664000000","2"],["1469836800000","1"],["1470096000000","12"]]},{"key":"Africa","values":[["1470096000000","1"]]},{"key":"UK","values":[["1469664000000","3"],["1469750400000","3"],["1469836800000","1"],["1469923200000","2"],["1470009600000","4"],["1470096000000","2"]]}];
data.forEach(function (o) {
o.values.forEach(function (values) {
values.forEach(function (value, i) {
values[i] = parseInt(value, 10);
});
});
});
console.log(JSON.stringify(data, null, 4));
var data = [{"key":"America","values":[["1469664000000","1"],["1469750400000","13"],["1469836800000","2"],["1469923200000","1"],["1470009600000","1"],["1470096000000","1"]]},{"key":"India","values":[["1469750400000","1"]]},{"key":"China","values":[["1469664000000","2"],["1469836800000","1"],["1470096000000","12"]]},{"key":"Africa","values":[["1470096000000","1"]]},{"key":"UK","values":[["1469664000000","3"],["1469750400000","3"],["1469836800000","1"],["1469923200000","2"],["1470009600000","4"],["1470096000000","2"]]}];
data = data.map(function(t){
var newVals = t.values.map(function(vs){
return vs.map(function(v){
return parseInt(v, 10);
});
});
return {'key': t.key, values: newVals};
});
console.log(JSON.stringify(data));
You can use JSON.parse(your json object
or maybe use two forEachs

Access Json array

I have the following JSON I get sent back from my database and I am trying to access the 'name' and 'contact's keys:
[
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
},
{
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}
]
My java script callback function looks something like this and inside I am trying to print the values from the entities variable:
dataset.get(keys, function(err, entities) {});
I tried: entities.key.name[0] to get the first name key value, but it does not work. I am also stuck how to then get the contacts variable.
You can try something like this:
var json = [{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
}, {
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}]
function getJSONValues(){
var names = [], contacts = [];
for (var obj in json){
console.log(json[obj]);
names.push(json[obj].key.name);
contacts.push(json[obj].data.contacts.splice(0));
}
console.log(names, contacts)
}
getJSONValues();
Use console to see what is what:
var entities = [
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
},
{
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}
];
console.log(entities);
console.log(entities[1].key.name);
console.log(entities[1].data.contacts[0]);
if the variable to which this JSON object is assigned to is entities
then
entities[ 0 ][ "key" ].name; //will give you name
entities[ 0 ][ "data" ].contacts; //will give you contacts
now you can iterate the entities as
entities[ counter ][ "key" ].name; //will give you name
entities[ counter ][ "data" ].contacts; //will give you contacts
You have an array. So you have to use an index to read an item from it.
entities[0]
returns the first object.
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
}
The you can use either the dot notation or brackets notation to read the values of your object. For instance, if you want to read the key, just try this:
entities[0].key
Now key has a reference to the following object:
{
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
}
So, if you want to get the name, just do one more step:
entities[0].key.name
The same holds for the contacts:
entities[0].data.contacts
Use entities[ 0 ][ "key" ].name; as entities is an array

How to convert an array to object in this special case?

I am converting some data in order to send it to the frontend in a readable way.
I just convert some XML data into JSON, and I am getting an object, but every value is key : ['value'], and I need it key: 'value'
I am sending the data like this res.status(200).json({dealersData}); where dealersData returns this
{
"dealersData": [
{
"DealerId": [
"1"
],
"DealerName": [
"Carmen"
],
"NickName": [
"Carmen"
],
"Picture": [
"00001.jpg"
],
"Active": [
"1"
],
"LegalId": [
"111111111"
],
"TypeId": [
"1"
]
},
{
"DealerId": [
"14"
],
"DealerName": [
"Jaz"
],
"NickName": [
"Jaz"
],
"Active": [
"1"
],
"LegalId": [
"111111187"
],
"TypeId": [
"1"
]
}
]
}
so as you can see I am getting the data "TypeId":["1"] and so on, and I don't want like that, I want "TypeId" : 1, so what should I do to translate that arrays into objects hopefully using Lodash ?
For each dealer iterate over the keys and replace the value with value[0].
dealersData = dealersData.map( function( dealer ){
Object.keys( dealer ).forEach( function(key){
dealer[key] = dealer[key][0];
})
return dealer;
});
http://jsfiddle.net/r38u4qag/1/ (or ES2015 fat arrow version: http://jsfiddle.net/r38u4qag/2/)
This will recursively step through the object, changing arrays of length one to strings:
function process(obj) {
for(var key in obj) {
if(obj[key] instanceof Array && obj[key].length==1) {
obj[key]= obj[key][0];
}
else if(obj[key] instanceof Object) {
process(obj[key]);
}
}
} //process
function process(obj) {
for(var key in obj) {
if(obj[key] instanceof Array && obj[key].length==1) {
obj[key]= obj[key][0];
}
else if(obj[key] instanceof Object) {
process(obj[key]);
}
}
} //process
var obj= {
"dealersData": [
{
"DealerId": [
"1"
],
"DealerName": [
"Carmen"
],
"NickName": [
"Carmen"
],
"Picture": [
"00001.jpg"
],
"Active": [
"1"
],
"LegalId": [
"111111111"
],
"TypeId": [
"1"
]
},
{
"DealerId": [
"14"
],
"DealerName": [
"Jaz"
],
"NickName": [
"Jaz"
],
"Active": [
"1"
],
"LegalId": [
"111111187"
],
"TypeId": [
"1"
]
}
]
}
process(obj);
document.querySelector('pre').innerHTML= JSON.stringify(obj,'\n',2);
<pre></pre>
If I get it right, you have arrays, but you don't need them, since you will always return just a single value, right?
If that's the case, you just have to call .toString() method on your arrays object. I would iterate over your dealersData to do that on all arrays:
for(var i = 0; i < dealersData.length; i++) {
dealersData[i].DealerId = dealersData[i].DealerId.toString();
dealersData[i].DealerName = dealersData[i].DealerName.toString();
[...]
}

Categories

Resources