How to use received data by ajax? - javascript

This code works well and I am receiving data from server. Data consists of [{id: someId, name: someName}, {..}....{...}]
SJA.ajax(dataToSend, function (respond) {
if (respond) {
for (var i in respond) {
console.log(respond[i].id);
console.log(respond[i].name);
}
}
});
How can I create an array from only respond[i].name and use this array in such a way:
var data = ["name", "name", "name"];

Simply
var names = respond.map(function(r) { return r.name; });
will do what you want.

var data = $.map(respond, function (v) { return v.name; });

Related

Filter data inside array object of array object using javascript

I am trying to filter data inside array object of array object, Please find below code for more information.
var data = [
{
name:'testdata1',
subdata:[{status:'fail'},{status:'success'}]
},
{
name:'testdata2',
subdata:[{status:'fail'},{status:'success'}]
}
]
Expected Data:
var successdata = [
{
name:'testdata1',
subdata:[status:'success'}]
},
{
name:'testdata2',
subdata:[status:'success'}]
}
];
var FailureData =[
{
name:'testdata1',
subdata:[{status:'fail'}]
},
{
name:'testdata2',
subdata:[{status:'fail'}]
}
];
I missed curly braces,So i am updating
Hope this helps.
const data = [{
name: 'testdata1', subdata: [{status: 'fail'}, {
status:
'success'
}]
},
{
name: 'testdata2', subdata:
[{status: 'success'}, {status: 'fail'}]
}
];
const filterData = (data, status) => data.reduce((acc, val) => {
const sub = val.subdata.map((v) => v.status === status ? ({ name: val.name, subdata: [v] }) : null).filter(f => f !== null);
return acc.concat(sub);
}, []);
const successData = filterData(data, 'success');
const failureData = filterData(data, 'fail');
console.log('successData', successData);
console.log('failureData', failureData);
You could map your arrays using Array.map():
var successData = data.map(item => ({name: item.name, subdata:[{status:'success'}]})
What I guess you want to do is filter the array based on subdata status.
I also guess that what subdata should have is just the status property and your code would be: var data = [{name:'testdata1',subdata:[{status:'fail'},{status:'success'}] }.
Then you want to look in the subdata array and find which data have success and failure in them.
So what you could be looking for is this:
var successData = data.filter(sdata => {
var successFlag=false;
sdata.subdata.forEach(subdata=>{
if (subdata.status==='success'){
successFlag = true;
}
}
return successFlag;
}
The same with the failureData.
For more information you could check the Array.prototype.filter function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
P.S. As mentioned in a comment to your question as well, your subdata array cannot be an object with two of the same property
var data = [{name:'testdata1',subdata:[{status:'fail'}, {status:'success'}] },{name:'testdata2',subdata:[{status:'success'}, {status:'fail'}] }]
var successData = filterByStatus('success', data);
var failureData = filterByStatus('fail', data);
function filterByStatus(status, data) {
return data.map(d => {
var newObj = Object.assign({}, d);
newObj.subdata = newObj.subdata.filter(s => s.status === status);
return newObj;
});
}
console.log('successData', successData);
console.log('failureData', failureData);
one of possible ways to do what you want if you have one success property in your object

Javascript forEach where value equals value in different array

Javascript:
$(document).ready(function() {
const ores = "../js/json/oreList.json";
const priceURL = "https://esi.tech.ccp.is/latest/markets/prices/?datasource=tranquility";
let oreArray = [];
let priceArray = [];
let total = 0;
// Retrieve list of ores
function getOres() {
$.getJSON(ores, function(ores) {
ores.forEach(function(ore) {
total++;
if (total === 48) {
getPrices();
}
oreArray.push(ore);
});
});
}
// Retrieve all items & prices via API
function getPrices() {
$.getJSON(priceURL, function(prices) {
prices.forEach(function(data) {
priceArray.push(data);
console.log(data);
});
});
}
getOres();
});
The first function creates an internal array from my .JSON file and the second function creates an internal array from the URL.
In the first array oreArray, an object looks like this:
{ id: 1234, name: "Title" }
In the second array priceArray, an object looks like this:
{ type_id: 1234, average_price: 56.34 }
My oreArray has 48 objects and unfortunately the priceArray has about 11,000 objects. I need to create a new array by comparing the two arrays and building new objects, where the ID's match. So for example objects in newArray would look like:
{ id: 1234, name: "Title", average_price: 56.34 }
Basically I'm having trouble figuring out the logic for:
For each object in oreArray, find the object with the same ID value in priceArray and append the new array with a new object using values from both arrays.
I would do it this way:
const ores = "../js/json/oreList.json",
priceURL = "https://esi.tech.ccp.is/latest/markets/prices/?datasource=tranquility";
let oreArray,
priceArray,
joinedArray = [];
function getOres() {
$.getJSON(ores, function(ores) {
oreArray = ores;
getPrices();
});
}
function getPrices() {
$.getJSON(priceURL, function(prices) {
priceArray = prices;
joinPrices();
});
}
function joinPrices() {
oreArray.forEach(function(ore) {
var matchingPrice = getMatchingPrice(ore);
if(matchingPrice !== false) {
joinedArray.push({
id: ore.id,
name: ore.name,
average_price: matchingPrice.average_price
});
}
});
}
function getMatchingPrice(ore) {
for(var i=0; i<priceArray.length; i++) {
if(priceArray[i].type_id === ore.id) {
return priceArray[i];
}
}
return false;
}
getOres();
I think that a good way to approach this problem is by changing the data structure of the average prices a little bit.
Instead of having them in an array, where each item has type_id and average_price field, you might want to consider using an object to store them, where the key is the type_id and the value is the average_price.
To be more concrete, you can replace:
prices.forEach(function(data) {
priceArray.push(data);
});
With:
const pricesMap = {};
prices.forEach(price => {
pricesMap[price.type_id] = price.average_price
});
And when looping on the oreArray, you can access each product's average_price by simply referring to pricesMap[ore.id]
You can check out this JSBin: http://jsbin.com/fogayaqexe/edit?js,console
You can use reduce to loop over each oreArr item and collect the data you need in the accumulator:
var oreArr=[
{ id: 1234, name: "Title" },
{ id: 2234, name: "2Title" },
]
var priceArr= [
{ type_id: 1234, average_price: 56.34 },
{ type_id: 2234, average_price: 256.34 },
{ type_id: 3234, average_price: 56.34 },
{ type_id: 4234, average_price: 56.34 },
]
var resArr = oreArr.reduce((ac,x) => {
var priceMatch = priceArr.find( z => z.type_id === x.id )
if(! priceMatch)
return ac //bail out if no priceMatch found
var res = Object.assign({}, x, priceMatch)
ac.push(res)
return ac
},[])
console.log(resArr)
other methods used:
arrayFind to check intersection
Object.assign to create the merged object to populate the accumulator
I suggest you to change your small json as object
eg : '{"1234":{"id": 1234, "name": "Title" }}';
var json = '{"1234":{"id": 1234, "name": "Title" }}';
oreArray = JSON.parse(json);
alert(oreArray['1234'].name); // oreArray[priceArraySingle.id].name
we can easily match priceArray id with oreArray.

Accessing the query variable from within callback

Take the following example:
getOptions() {
let options = {};
if (this.props.location.hasOwnProperty('query')) {
const query = this.props.location.query;
const queriesMap = {
'createdBy': 'createdBy',
'state': 'state',
'created_from': 'created_at[from]',
'created_to': 'created_at[to]'
};
Object.keys(query).map(function(key) {
if(queriesMap.hasOwnProperty(key)) {
options = Object.assign(options, { queriesMap[key]: query[key] });
}
});
}
return options;
}
I'm using the queriesMap object to map url parameters to build a new url to call an API. The problem is that query is undefined when I'm trying to access it from within the .map callback.
How do I access the query variable?
Looks like you are missing a [] around queriesMap[key]. So it should be options = Object.assign(options, { [queriesMap[key]]: query[key] });.
Also, you could just do options[queriesMap[key]] = query[key] rather than Object.assign

Use function to rewrite JSON object keys?

I have a program and want to change the object key names in a JSON file with a function. I have already created a function that changes the keys when it is displayed via Angular, but I want to create a function that allows me to change the object key names directly in the JSON file.
Here is a sample of my JSON file ( the actual array contains over 300 entries ):
[
{
"FIELD1":"key",
"FIELD2":"company",
"FIELD3":"team",
"FIELD4":"num_female_eng",
"FIELD5":"num_eng",
"FIELD6":"percent_female_eng",
"FIELD7":"last_updated",
"FIELD8":"Submit more data!",
"FIELD9":"https://github.com/triketora/women-in-software-eng"
},
{
"FIELD1":"all",
"FIELD2":"ALL",
"FIELD3":"N/A",
"FIELD4":"2798",
"FIELD5":"14810",
"FIELD6":"18.89",
"FIELD7":"11/18/2015",
"FIELD8":"",
"FIELD9":""
},
{
"FIELD1":"wellsfargo",
"FIELD2":"Wells Fargo",
"FIELD3":"N/A",
"FIELD4":"1296",
"FIELD5":"5407",
"FIELD6":"23.97",
"FIELD7":"7/22/2015",
"FIELD8":"",
"FIELD9":""
}
]
and what I have done thus far to change the key names:
(function() {
'use strict';
angular
.module("app.companies")
.controller('CompaniesCtrl', CompaniesCtrl);
CompaniesCtrl.$inject = ['$scope', 'CompanyFactory'];
function CompaniesCtrl($scope, CompanyFactory) {
$scope.work = "i work";
$scope.companies = CompanyFactory;
$scope.makeChart = function(company){
$scope.femaleDevs = parseInt(company.num_female_eng);
$scope.allDevs = parseInt(company.num_eng);
$scope.company = company.company;
$scope.maleDevs = $scope.allDevs - $scope.femaleDevs;
console.log($scope.maleDevs);
};
}
})();
Thank you for all of your help :) !
Maybe this should help you:
var fieldsmap = {
'FIELD1': 'key',
'FIELD2': 'company',
'FIELD3': 'team',
'FIELD4': 'num_female_eng',
'FIELD5': 'num_eng',
'FIELD6': 'percent_female_eng',
'FIELD7': 'last_updated',
'FIELD8': 'name2',
'FIELD9': 'name3'
};
function renameObjectKeys(obj) {
for (var key in fieldsmap) {
if (obj.hasOwnProperty(key) && fieldsmap.hasOwnProperty(key)) {
obj[fieldsmap[key]] = obj[key]; //copy the key into new key
delete(obj[key]); // delete old key
}
}
}
myArray.forEach(function(object) {
renameObjectKeys(object);
});

How to convert an object of objects to an array of objects?

I have an external file people.json. How I can convert it to a javascript array with json syntax?
this is the people.json content:
{
"1":{
"Name":"Jhon",
"Surname":"Kenneth",
"mobile":329129293,
"email":"jhon#gmail.com"
},
"2":{
"Name":"Thor",
"Surname":"zvalk",
"mobile":349229293,
"email":"thor#gmail.com"
},
"3":{
"Name":"Mila",
"Surname":"Kvuls",
"mobile":329121293,
"email":"mila#gmail.com"
}
}
I want an array with this format
var person = [
{ "name":"jhon" , "surname":"kenneth", "mobile":329129293, "email":"jhon#gmail.com"},
{ "Name":"Thor", "Surname":"zvalk", "mobile":349229293, "email":"thor#gmail.com" },
{ "Name":"Mila", "Surname":"Kvuls", "mobile":329121293, "email":"mila#gmail.com"}
];
I tried with the next code, but it doesnt worker:
var person;
$.getJSON('people.json', function (json) {
person[]= json
});
By the way, the file contacts.json is in my server.
Can use jQuery $.map()
var newArray=$.map( originalObject, function(item){
return item;
})
DEMO: http://jsfiddle.net/qmfn2/
Try like this:
$.getJSON('people.json', function (json) {
var people = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
people.push({
name: item.Name,
surname: item.Surname,
mobile: item.mobile,
email: item.email
});
}
}
// at this stage the people object will contain the desired output
});
First you will need to fetch the JSON file using an AJAX request. Then iterate through the received JSON object and add each property to an array.
function convertToArray (receivedObj) {
var array = [], key;
for (key in receivedObj) {
array.push(receivedObj[key]);
}
return array;
}
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});
Hope this helps!
Like this:
var array = $.map($.parseJSON(data), Object);
http://jsfiddle.net/mXFKL/
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});

Categories