Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
var result = [
{
"Name": "abc",
"age": 12,
"City": "Mumbai",
"id":"U121"
},
{
"Name": "jkl",
"age": 22,
"City": "Mumbai",
"id":"U122"
},
{
"Name": "xyz",
"age": 32,
"City": "Mumbai",
"id":"U123"
},{
"Name": "mno",
"age": 42,
"City": "Mumbai",
"id":"U124"
}
]
I want to iterate this in javascript and create td, tr element in such a way that abc, jkl come in one row and xyz, mno come in second row. Can anyone help me with the logic?
You can try something like this
var input = [
{
"Name": "abc",
"age": 12,
"City": "Mumbai",
"id":"U121"
},
{
"Name": "jkl",
"age": 22,
"City": "Mumbai",
"id":"U122"
},
{
"Name": "xyz",
"age": 32,
"City": "Mumbai",
"id":"U123"
},{
"Name": "mno",
"age": 42,
"City": "Mumbai",
"id":"U124"
}
];
function test(){
let i=0;
let outhtml="";
input.forEach(ele => {
i=i%2;
let addRow=(i==0);
//After 2 elements add row
if (addRow){
outhtml += "</tr><tr>"
}
//add td
outhtml += "<td>"+ele.Name+"</td>"
i++;
})
//Remove </tr> from start
outhtml = outhtml.substring(5, outhtml.lenght);
document.getElementById("mytable").innerHTML = outhtml;
}
test();
<table id="mytable">
</table>
Related
This question already has answers here:
Javascript group a JSON object by two properties and count
(7 answers)
Group and count values in an array
(4 answers)
Closed 1 year ago.
Given a sample JSON array of objects, like this....
[
{
"firstName": "Bob",
"lastName": "Smith",
"city": "Preston",
"st": "Florida",
"age": 15
},
{
"firstName": "Tom",
"lastName": "Jones",
"city": "Springfield",
"st": "Illinois",
"age": 34
},
{
"firstName": "Mary",
"lastName": "Hart",
"city": "Miami",
"st": "Florida",
"age": 22
},
{
"firstName": "Jenny",
"lastName": "Dixon",
"city": "Palm City",
"st": "Florida",
"age": 26
}
]
What is the best way to get the number of occurrences based on the groupings of a particular property? So, let's say I want to produce a JSON object that has each unique state ("st") and the number of occurrences....
[
{
"st": "Illinois",
"count": 1
},
{
"st": "Florida",
"count": 3
}
]
I can do it manually using a for-let, looping through the array, tracking the values as I loop, etc. But I'm sure there's a more efficient way using ES6. Can you please help me out? Thanks.
You can use Array#reduce to keep a tally
let counts = json.reduce((b, a) => {
let index = b.findIndex(j => j.st === a.st);
if (index > -1) b[index].count++;
else b.push({st: a.st, count: 1});
return b;
}, [])
#UPDATE: As mentioned by #epascarello, there is a more efficient way to go about this, removing the findIndex loop and using Object.values
const results = Object.values(json.reduce((obj, item) => {
obj[item.st] = obj[item.st] || { st: item.st, count: 0 };
obj[item.st].count++;
return obj;}, {}))
let json = [{
"firstName": "Bob",
"lastName": "Smith",
"city": "Preston",
"st": "Florida",
"age": 15
},
{
"firstName": "Tom",
"lastName": "Jones",
"city": "Springfield",
"st": "Illinois",
"age": 34
},
{
"firstName": "Mary",
"lastName": "Hart",
"city": "Miami",
"st": "Florida",
"age": 22
},
{
"firstName": "Jenny",
"lastName": "Dixon",
"city": "Palm City",
"st": "Florida",
"age": 26
}
]
let counts = json.reduce((b, a) => {
let index = b.findIndex(j => j.st === a.st);
if (index > -1) b[index].count++;
else b.push({st: a.st, count: 1});
return b;
}, [])
console.log(counts)
const results = Object.values(json.reduce((obj, item) => {
obj[item.st] = obj[item.st] || { st: item.st, count: 0 };
obj[item.st].count++;
return obj;}, {}))
console.log(results)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have the following data structure:
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
Using Ramda I would like to transforms it into:
const result = [
{
"firstName": "A",
"lastName": "B",
"address": {
"country": "France",
"city": "Paris"
},
},
{
"firstName": "A",
"lastName": "B",
"address": {
"country": "Italy",
"city": "Rome"
},
},
];
You can use a converge function to fork the prop address and then join it with the main object for each address in the list:
/**
* R.pick could be replaced with R.omit
* to let you black list properties:
* R.omit(['address']); https://ramdajs.com/docs/#omit
**/
const createByAddress = R.converge(R.map, [
R.pipe(R.pick(['firstName', 'lastName']), R.flip(R.assoc('address'))),
R.prop('address'),
]);
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
console.log(createByAddress(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
My question is why "with Ramda"? I'm a founder of Ramda and a big fan, but it's just a tool, and unless this is a learning exercise for Ramda, it doesn't seem like there is any need to use it for this problem.
I would do it like this, using modern JS techniques:
const transform = ({address, ...rest}) =>
address .map (a => ({...rest, address: a}))
const data = {firstName: "A", lastName: "B", address: [{country: "France", city: "Paris"}, {country: "Italy", city: "Rome"}]}
console .log (
transform (data)
)
I am not sure if this will help you but if you want to generate multiple objects based on adress maybe this helps
const obj = {
firstName: "a",
lastName: "b",
adresses: [{
country: "France",
city: "Paris"
}, {
country: "Italy",
city: "Rome"
}]
};
adressAmount = obj.adresses.length;
const adressObjects = [];
for (let i = 0; i < adressAmount; i++) {
const {
adresses,
...objWithoutAdresses
} = obj;
objWithoutAdresses.adress = obj.adresses[i];
adressObjects.push(objWithoutAdresses);
}
console.log(adressObjects);
I found this pretty simple and short.
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
let requiredData = data.address.map(element=>{
return {...data,address:element}
})
console.log(requiredData);
1) Create an empty dictionary
2) for loop the array and store index of each array in the dictionary as value
You can iterate the address array and create object as required
let obj = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
]
}
let newData = obj.address.map(function(item) {
return {
firstName: obj.firstName,
lastName: obj.lastName,
address: {
country: item.country,
city: item.city
}
}
});
console.log(newData)
I'm trying to access specific data from json array. and i'm using dynamic dropdown.
So in my case i want get all names from the json and plot it on option.
here is the Json we're accessing..
[
{
"id": 1,
"name": "john"
"age": 23,
"city": "New York"
},
{
"id": 2,
"name": "Donald"
"age": 34,
"city": "London"
},
{
"id": 3,
"name": "k'nan"
"age": 27,
"city": "Paris"
},
{
"id": 1,
"name": "jose"
"age": 29,
"city": "lesbon"
},
]
script
$.each(data, function(key,vlaue ){
$('select[name="bus_number"]').append('<option value="'+ key +'">'+ value +'</option>');
});
and again i want to access only all names and plot it on options.
i did this and it's not working and may be you guys will tell me a better way.
Brb to explain soon.
Jquery:
var data = [
{
"id": 1,
"name": "john",
"age": 23,
"city": "New York"
},
{
"id": 2,
"name": "Donald",
"age": 34,
"city": "London"
},
{
"id": 3,
"name": "k'nan",
"age": 27,
"city": "Paris"
},
{
"id": 1,
"name": "jose",
"age": 29,
"city": "lesbon"
},
];
$.each( data, function( index, object ) {
$('select[name="bus_number"]').append('<option value="'+ object['id'] +'">'+ object['name'] +'</option>');
});
I'm assuming that you are trying to create a dropdown where the options' labels are the names in the data and the options' values are the corresponding ids.
data.forEach(({id, name}) => {
$('select[name="bus_number"]').append(`<option value="${id}">${name}</option>`);
});
Notice that I use JavaSctipt's native forEach instead of jQuery's (no need for that anymore), and I'm also using Object Desctructuring and String Literals which make your code easier to read.
Here's a fiddle.
I have a collection of objects in an array like this:
[
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
},...
]
In my view I only want to display Name, Age, City and Country. Well, my question is how can I remove GROUP_ID and ACTIVE in every object of my collection? I was looking for a solution and found .slice() but I don't know exactly whether is it the right one and how to use this javascript function for each object in an array.
EDIT:
For more clarification. My view is defined like below:
<md-list-item ng-repeat="cItems in ::contentItems track by $index">
<span ng-repeat="(key, value) in cItems track by $index" flex="auto">
{{ ::value }}
</span>
<md-divider></md-divider>
</md-list-item>
You can use the following lines:
contentItems.forEach(function (entry) {
delete entry['GROUP_ID'];
delete entry['ACTIVE'];
});
As mentioned in comments there is no need to delete the keys. You can simple avoid displaying them.
Still if deleting is objective then use delete method
a.forEach(function(item){
delete(item['GROUP_ID']);
delete(item['ACTIVE'])
});
DEMO
Assuming your array is a variable named array:
for ( var i=0,l=array.length; i<l; i++ ) {
delete array[i]['GROUP_ID'];
delete array[i]['ACTIVE'];
}
if you're using ES6 you could also do:
for ( let item of array ) {
delete item['GROUP_ID'];
delete item['ACTIVE'];
}
You can simply remove properties of an object by using delete. I've added an array of properties to delete but you could delete them directly.
var data = [
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
}
];
var propertiesRemove = ['GROUP_ID', 'ACTIVE']
data.forEach(function(item){
propertiesRemove.forEach(function(prop){
delete item[prop];
});
});
console.log(data);
If you don't want to change your data and it's just a display issue you could render only the properties you want.
<md-list-item ng-repeat="cItems in ::contentItems track by $index">
<span flex="auto">{{cItems.NAME}}</span>
<span flex="auto">{{cItems.AGE}}</span>
<span flex="auto">{{cItems.CITY}}</span>
<span flex="auto">{{cItems.COUNTRY}}</span>
<md-divider></md-divider>
</md-list-item>
Actually to display required information in angular we don't need to remove other elements from array in template we can go with limited information.
ANGULAR CODE
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
}
]
});
Angular Template
<body ng-app="myApp" ng-controller="myCtrl">
<ul ng-repeat="record in records">
<li>{{record.NAME}}</li>
<li>{{record.AGE}}</li>
<li>{{record.COUNTRY}}</li>
</ul>
But as you are asking following procedure will answer your question.
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$data = [
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
}
];
$scope.records = $data.map(function(item){
delete(item['GROUP_ID']);
delete(item['ACTIVE']);
return item;
});
});
This question already has answers here:
Sorting Object by sub-object property
(4 answers)
Closed 7 years ago.
How to sort the objects by age value?
I have the following object structure
{
"men": {
"20114": {
"id": "20114",
"name": "Peter",
"age": "21"
},
"28957": {
"id": "28957",
"name": "Paul",
"age": "20"
}
},
"women": {
"8957": {
"id": "8957",
"name": "Rose",
"age": "24"
},
"2178": {
"id": "2178",
"name": "Sara",
"age": "22"
}
},
}
I know, that I can sort arrays like this
groups.sort(function(a, b) {
return b.age - a.age;
});
but how to do this with objects?
It would be a lot easier to sort your data if you could change your structure to the JSON model below:
var data = [
{
"id": "20114",
"name": "Peter",
"age": "21",
"gender": "men"
},
{
"id": "28957",
"name": "Paul",
"age": "20",
"gender": "men"
},
{
"id": "8957",
"name": "Rose",
"age": "24",
"gender": "women"
},
{
"id": "2178",
"name": "Sara",
"age": "22",
"gender": "women"
}
]
data.sort(function(a, b) {
return parseFloat(a.age) - parseFloat(b.age);
});
data.sort()
document.write(JSON.stringify(data))
function sortfunc(prop){
return function(obj1,obj2){
var val1 = obj1[prop];
var val2 = obj2[prop];
return val1 - val2;
};
}
groups.sort(sortfunc(prop));
pass prop as property name