How do I map an array of objects - javascript

I can't figure this out and I've been at it for hours, so let's say I have an array of JSON. I want to map out the data into a new array.But I am stuck, could someone explain how to use map properly with an array of Json objects, thanks.
var results = [{
"userid": 1213,
"name": "jake",
"id": 3242,
"state": "ny"
}, {
"userid": 1203,
"name": "phil",
"id": 3142,
"state": "ny"
}, {
"userid": 1013,
"name": "kate",
"id": 3241,
"state": "js"
}];
$.ajax({
dataType: "json",
data: results,
success:function(data){
$.map(data.results, (dat, item) {
var array = new Array();
var groups;
groups = array;
groups.a = dat.userid;
groups.b = dat.name;
groups.c = dat.state;
array.push(groups);
} })
});

Map your array before calling $.ajax();
results = results.map(function(item) {
return {
a: item.userid,
b: item.name,
c: item.state;
};
});
//DO your thing
$.ajax({
dataType: "json",
data: results
});

You just forget return mapped obj.
var results = [{
"userid": 1213,
"name": "jake",
"id": 3242,
"state": "ny"
}, {
"userid": 1203,
"name": "phil",
"id": 3142,
"state": "ny"
}, {
"userid": 1013,
"name": "kate",
"id": 3241,
"state": "js"
}];
console.log($.map(results, function(dat, item) {
var groups = {};
groups.a = dat.userid;
groups.b = dat.name;
groups.c = dat.state;
return groups;
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

First thing, you need to put your mapping code inside an ajax callback. Then, you can use either jQuery map or javascript map or simple for loop to iterate through each item in the response array.
$.ajax({
dataType: "json",
data: results,
success: function( data )
{
var groups = data.map(function(currentItem){
var group = {};
group.a = currentItem.userid;
group.b = currentItem.name;
group.c = currentItem.state;
return group;
});
console.log( groups );
}
});

Related

How can I dynamically remove a parent in JSON with JS?

With some JavaScript, how can I transform a JSON from:
{
"d": {
"__count": "13",
"results": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
}
TO
{
"__count": "13",
"data": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
Basically removing the extra "d" parent and renaming results to data? I am using this in the context of vue-table in VueJS.
Assumed that you have the json saved in a variable 'data':
data = data.d
data.data = data.results
delete data.results
This function will do it.
function transform(json) {
var obj = JSON.parse(json);
obj.d.data = obj.d.result;
delete obj.d.result;
return JSON.stringify(obj.d);
}
One solution is to unserialize your JSON to have an object (JSON.parse()). Then to serialize only what you need (JSON.stringify()).
You can use a loop.
var res = [];
for(var k in jsonData){
res.push(jsonData[k]);
}
var jsonData = {
"d": {
"__count": "13",
"results": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
};
console.log(jsonData);
var res = [];
for(var k in jsonData){
res.push(jsonData[k]);
}
console.log("result:");
console.log(res);

Add array to an object inside of an array in state

So say I have an array like so:
this.state = {
students: [{
"company": "This",
"firstName": "Randy",
"id": "1",
"lastName": "Orton",
},
{
"company": "That",
"firstName": "Clark",
"id": "2",
"lastName": "Kent",
}]
}
I would like to add an array to the first object so it looks like this.
this.state = {
students: [{
"company": "This",
"firstName": "Randy",
"id": "1",
"lastName": "Orton",
"array" : []
},
{
"company": "That",
"firstName": "Clark",
"id": "2",
"lastName": "Kent",
}]
}
How can I go about doing that without messing with initial state but only update it?
You can try to use these following ways:
this.state.students[0].array = [];
this.state.students.find(x => x.company === 'This').array = [];
After getting the response from server, you can add array property to each student object immediately:
Example:
var obj = {};
$.ajax({
type: 'POST',
url: '/yourAPIUrl'
}).done(function (response) {
obj.state = reponse;
for (var student of obj.state.students) {
student.array = [];
}
});

How to get Key and Value from JSON object in Javascript(Postman)

I have a JSON object like this, I wanna access the list array elements with key and value in postman.
{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}
How to separate it as Key and Value in Javascript like,
Key: id,name,mobileNo,address,city,..
Value: 53,Sonu,6543213456,Greeny Pathway,NewYork,....
First remove comma from line : "qty": null, otherwise it will cause error in json parsing.
var resultJSON = `{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}`;
var result = $.parseJSON(resultJSON);
var myList = result.data.list[0];
$.each(myList, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use below codes:
const keys = Object.keys(jsonObject);
const values = Object.values(jsonObject);
But your JSON object is deep, you should flatten it and then use keys and values of Object to make them separate.
You can get using key and value separately in a array.
var a = {
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null,
}
]
},
"success": true,
"message": ""
}
var keyval = Object.keys(a.data.list[0])
console.log(keyval)
var values = Object.values(a.data.list[0])
console.log(values)
JSON objects are key value pair you cannot get the keys and values in object form as you desire but you can get both in form of arrays from this code
var key = []
var values = []
list.map(function(l){ keys = Object.getOwnPropertyNames(l);
keys.map(function(key) {values.push(l[key]);})})
Finally this works for me!(In Postman Script)
var resdata = JSON.parse(responseBody);
console.log(resdata);
key = Object.keys(resdata.data.list[0]);
console.log(key);
value =Object.values(resdata.data.list[0]);
console.log(value);

Filter values of multiple properties with an array of values

So I really would like to make a duplicate out of my previous failed question because I wasn't really able to explain myself properly and thus didn't get the answer (and haven't really solved my issue).
There is the JSON:
[
{
"id": 2,
"name": "Google",
"country": "Sweden"
},
{
"id": 3,
"name": "Google",
"country": "USA"
},
{
"id": 9,
"name": "Google",
"country": "Ukraine"
},
{
"id": 10,
"name": "Bing",
"country": "Sweden"
}
]
What I failed to do previously I guess is to post what I have so far and explain better what I need. This is what I have right now:
$scope.loadSearchEngines = function ($query) {
return $http.get('search-engines.json', {cache: true}).then(function (response) {
var tags = response.data;
return tags.filter(function (tag) {
return tag.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
});
});
};
This filter restricts me to search through only the name property, while ideally I would like to search through any property (or well, all the properties, rather) and I'd like the filter to work with an array of parameters so that each word would separately look through each property in the object and find a match.
In the previous post a person posted a for loop for it, but that is exactly the kind of unintuitive thing I want to avoid.
I know what I want the result to be but I just can't think of an approach (lodash/underscore seemingly almost does something like this, but I think there is something missing from somewhere or I am really bad at understanding the docs).
Examples:
In case I write "google sweden", it will only show the 1 result, if I write "sweden", it would show the one from google and the one from bing.
In case I write "in", it should show "bINg" and google "ukraINe" I guess.
This seemed like a much less of a hassle at first but I can't really wrap my head around this using a filter. I really don't have any ideas to post because they have been embarrassingly bad and this is a really grey area for me.
From the question it looks as if you want to filter a list where the values in each item contains every keyword:
var keywords = ['Google', 'Sweden'];
var result = _.filter(data, function(item){
return _.every(keywords, function(keyword){
return _.some(item, function(value){
return _.isString(value) && value.indexOf(keyword) != -1;
})
});
});
Perhaps something like this (note, probably not the most efficient one). Doesn't handle lowercase, but it's simple to add.
http://jsfiddle.net/W4QfJ/520/
var stuff = [
{
"id": 2,
"name": "Google",
"country": "Sweden"
},
{
"id": 3,
"name": "Google",
"country": "USA"
},
{
"id": 9,
"name": "Google",
"country": "Ukraine"
},
{
"id": 10,
"name": "Bing",
"country": "Sweden"
}
];
var searchTerm = 'Google Sweden';
var searchTermArr = searchTerm.split(' ');
var results = [];
var obj;
searchTermArr.forEach(function (val, index, arr) {
obj = _(stuff)
.filter(function (s) {
return JSON.stringify(s).indexOf(val) > -1;
}).value();
results = results.concat(obj);
});
console.log(_.unique(results));
Version A shapes the result for the whole data set to the wanted set which iterates throu the search words.
var data = [{
"id": 2,
"name": "Google",
"country": "Sweden"
}, {
"id": 3,
"name": "Google",
"country": "USA"
}, {
"id": 9,
"name": "Google",
"country": "Ukraine"
}, {
"id": 10,
"name": "Bing",
"country": "Sweden"
}];
function search(s) {
var searchA = s.split(' ').map(function (a) { return a.toLowerCase(); });
var result = JSON.parse(JSON.stringify(data));
searchA.forEach(function (a) {
result = result.reduce(function (res, el) {
var i;
for (i in el) {
if (~('' + el[i]).toLowerCase().indexOf(a)) {
res.push(el);
break;
}
}
return res;
}, []);
});
return result;
}
out('search for \'google sweden\'\n' + JSON.stringify(search('google sweden'), null, 4), true);
out('search for \'bing\'\n' + JSON.stringify(search('bing'), null, 4), true);
out('search for \'IN\'\n' + JSON.stringify(search('IN'), null, 4), true);
out('search for \'x\'\n' + JSON.stringify(search('x'), null, 4), true);
function out(s, pre) {
var descriptionNode = document.createElement('div');
if (pre) {
var preNode = document.createElement('pre');
preNode.innerHTML = s + '<br>';
descriptionNode.appendChild(preNode);
} else {
descriptionNode.innerHTML = s + '<br>';
}
document.getElementById('out0').appendChild(descriptionNode);
}
<div id="out0"></div>
Version B with different approach. Here I collect the objects who match the requirements.
var data = [{
"id": 2,
"name": "Google",
"country": "Sweden"
}, {
"id": 3,
"name": "Google",
"country": "USA"
}, {
"id": 9,
"name": "Google",
"country": "Ukraine"
}, {
"id": 10,
"name": "Bing",
"country": "Sweden"
}];
function search(s) {
var searchA = s.split(' ').map(function (a) { return a.toLowerCase(); });
return data.reduce(function (res, el) {
var i, found = 0;
for (i in el) {
found += searchA.some(function (a) {
return ~('' + el[i]).toLowerCase().indexOf(a);
});
}
found === searchA.length && res.push(el);
return res;
}, []);
}
out('search for \'google sweden\'\n' + JSON.stringify(search('google sweden'), null, 4), true);
out('search for \'bing\'\n' + JSON.stringify(search('bing'), null, 4), true);
out('search for \'IN\'\n' + JSON.stringify(search('IN'), null, 4), true);
out('search for \'x\'\n' + JSON.stringify(search('x'), null, 4), true);
function out(s, pre) {
var descriptionNode = document.createElement('div');
if (pre) {
var preNode = document.createElement('pre');
preNode.innerHTML = s + '<br>';
descriptionNode.appendChild(preNode);
} else {
descriptionNode.innerHTML = s + '<br>';
}
document.getElementById('out').appendChild(descriptionNode);
}
<div id="out"></div>

How to merge two javascript arrays based on property values?

I have two arrays
array1 = [{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}]
array2 = [{"Deptid":1,"Deptname":"IT"},{"Deptid":12,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"}]
Output:
{ "0": { "id": 1, "name": "Michale Sharma", "gender": "Male", "age": 25, "salary": 10000, "Deptid": 1, "Deptname": "IT" }, "1": { "id": 2, "name": "Sunil Das", "gender": "Male", "age": 24, "salary": 5000}, "2": { "id": 3, "name": "Robin Pandey", "gender": "Male", "age": 35, "salary": 45000, "Deptid": 3, "Deptname": "HW" }, "3": { "id": 4, "name": "Mona Singh", "gender": "Female", "age": 27, "salary": 12000 }, "4" :{ "Deptid": 12, "Deptname": "HR" } }
I want to merge them based on the property values e.g id of array1 and Deptid of array2
Which means if id value = 1 and Deptid value = 1, then merge the records, if not then keep the values from one array and the other will be null. In another words, kind of the functionality of FULL OUTER JOIN. Because the array data cannot be a sequential one and may not be of the same length.
I have tried with Jquery.extend as under
$.extend(true, array1,array2)
It does not accept any property but merges the arrays.
I have also seen this but it does not help.
Looks like you need to have a custom logic. Here is sample using lodash library:
var array1 = [{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}]
var array2 = [{"Deptid":1,"Deptname":"IT"},{"Deptid":12,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"}]
var defaults = {
Deptid: null,
DeptName: null
};
_.each(array1, function (obj) {
var dept = _.find(array2, { Deptid: obj.id });
_.defaults(obj, dept, defaults);
});
Using LoDash, roughly something like this:
_.reduce(array1, function(res, item1) {
var found = _.find(array2, function(item2) {
return item1.id === item2.Deptid;
});
if (found) res.push(_.merge({}, item1, found));
return res;
}, []);
EDIT: Sorry, I forgot about merging empty props.
It would be something like this (unoptimized):
function join(array1, array2) {
var keys = _.keys(array2[0]);
var vals = _.map(keys, function() { return '' });
return _.map(array1, function(item1) {
var found = _.find(array2, function(item2) {
return item1.id === item2.Deptid;
});
if (found)
return _.merge({}, item1, found);
return _.merge({}, item1, _.zipObject(keys, vals));
}, []);
}

Categories