Append Multiple objects into single array - javascript

I have an array of objects of the structure coming from server response of iterated array object like as sample
array[1] ={
"ID": "123",
"Name": "John",
"Age": "15"
}
array[2] ={
"ID": "456",
"Name": "Sue",
"Age": "18"
}
array[n] ={
}
But now I want to append the array values if the condition age below 18 in the following structure of as iterated values of above array
Expected Output:
{
"Stud": [{
"ID": "123",
"Name": "John",
"Age": "15"
}, {
"ID": "456",
"Name": "Sue",
"Age": "18"
},{n........
}]
}

var output = { "Stud" : [] };
for (var i = array.length - 1; i >= 0; i--) {
if (array[i].Age < 18) {
output.Stud.push(array[i]);
}
}
console.log(output);

Simply
var output = { "Stud" : array }; //existing 'array'

You can use array#filter to select objects with age less than or equal to 18.
const response = [{
"ID": "123",
"Name": "John",
"Age": "15"
},{
"ID": "456",
"Name": "Sue",
"Age": "18"
},{
"ID": "459",
"Name": "Jaby",
"Age": "20"
}];
const result = response.filter(o => o.Age <= 18);
var output = {'stud' : result};
console.log(output);

Simply iterate and check whether the age is < 18 or not. If so push that to another array.
var array = [];
var array_below_18 = [];
array[0] ={
"ID": "123",
"Name": "John",
"Age": "15"
}
array[1] ={
"ID": "456",
"Name": "Sue",
"Age": "18"
}
array[1] ={
"ID": "456",
"Name": "Sue",
"Age": "14"
}
for(i=0;i<array.length;++i){
if(parseInt(array[i].Age)<18){
array_below_18.push(array[i]);
}
}
var final_object = {
"Stud" : array_below_18
}
console.log(final_object);

Related

Find object by property in JSON array

I have problem with get string in JSON data. Format as below:
[
{
"name": "Alice",
"age": "20"
},
{
"id": "David",
"last": "25"
},
{
"id": "John",
"last": "30"
}
]
Sometime it changes position together, John from 3rd place go to 2nd place:
[
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
]
If i use data[3].age to get John's age, and data change position, I will get David's age.
Is there any method I can use to find the object with name David and get the age value?
You can use array.find() method as,
var myArray = [
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
];
//Here you are passing the parameter name and getting the age
//Find will get you the first matching object
var result = myArray.find(t=>t.name ==='John').age;
console.log(result);
It's better to use array.filter() (better browser support)
myArray.filter(function(el){return el.name == "John"})[0].age

Find object index from array

I'm trying to find out selected object index from array
But it always return -1 don't know why?
Here is I'm trying to do
I have following array in which their are multiple objects
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}]
And here is my another array that are selected by user
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}]
Now I want to find out selected object index from data array and remove this object from that array
if (dList.length > 0) {
for (let i=0; i<dList.length; i++){
delete dList[i]['isChecked']
console.log(dList[i])
console.log(data[0])
console.log(dList[i] == data[0])
let index = data.indexOf(dList[i]);
console.log(index)
data.splice(index, 1);
}
}
Here is just a simple implementation:
if (dList.length > 0) {
for (let i=0; i<dList.length; i++) {
delete dList[i]['isChecked']
console.log(dList[i])
console.log(data[0])
console.log(JSON.stringify(dList[i]) === JSON.stringify(data[0]))
let index = data.findIndex(()=>dList[i]);
console.log(index)
data.splice(index, 1);
}
}
Comparing the objects can be done by just converting it into string using JSON.stringify(ObjectName).
Second instead of using indexOf use findIndex.
Here is the main difference between indexOf and findIndex.
You can only compare two primitive types only so you will not be able to get the index of the object by comparing it.
You should instead compare some primary key which will be unique for each object inside the array.
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}];
var index = data.findIndex(x => x.name=="abc2");
console.log(index);
this is going to meet your demand, a more universal version,if you got unique id,that is going to be the best choice:
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}
];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}];
dList.forEach(function(obj) {
delete obj.isChecked;
data.splice(data.findIndex((o) => {
return Object.getOwnPropertyNames(obj).every(p => obj[p] === o[p]);
}), 1);
});
console.log(data);
another way:
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}
];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}];
dList.forEach(function(obj) {
delete obj.isChecked;
data.splice(data.findIndex((o) => o.name === obj.name && o.age === obj.age && o.school === obj.school && o.school === obj.school), 1);
});
console.log(data);
unrecommended way:
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}
];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}];
dList.forEach(function(obj) {
delete obj.isChecked;
data.splice(data.findIndex((o) => JSON.stringify(o) === JSON.stringify(obj)), 1);
});
console.log(data);
You can use this also
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}]
console.log(data.map(function(d){
return d.name;
}).indexOf(dList[0].name));
You cannot compare two Object Notations(JSON). To compare two JSONs you need to first stringify the object, then JavaScript can compare the two objects for you.
Here is a simple code for you to get what you desire.
if (dList.length > 0) {
for(var i=0; i<data.length; i++){
for(var j=0; j<dList.length; j++){
delete dList[j]['isChecked'];
if(JSON.stringify(data[i]) === JSON.stringify(dList[j])){
let index = data.indexOf(data[i]);//Gets the index of the array
data.splice(index, 1);
console.log(data);
}else{
console.log('Data Not Matched in Array');
}
}
}
}
There is no generic means to determine that an object is equal to another in the sense. Please see Equality comparisons for more information.
You can find and remove objects like below:
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el.name === elem.name);
console.log(indexElement);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
data.remove(dList[0]);
console.log(data);
Online demo (jsFiddle)
var result= data.filter((item, i, self) => {
if (item.name === 'abc2') {
return { itemIndex: i, obj: item }
}
});
var output = result.map(r => { console.log(r.itemIndex) })
console.log(output);
This will return all objects in which name is abc2. findIndex array method will always return 1 index that might not be the case as people can have the same name.

How to add a name for each element of a list in Jackson

Is it possible to set a name for each element of a list in JSON using JACKSON?
For example, I have the following JSON:
{"result": [
{
"name": "ABC",
"age": "20"
},{
"name": "DEF",
"age": "12"
}
]}
But I need this:
{"result": [
person: { // << this is the name
"name": "ABC",
"age": "20"
},
person: {
"name": "DEF",
"age": "12"
}
]}
Thanks to everybody!
UPDATE
Hi people!
I made a mistake! The correct form is the following:
{"result": [
{
person: { // << this is the name
"name": "ABC",
"age": "20"
}
},
{
person: {
"name": "DEF",
"age": "12"
}
}
]}
In plain Javascript, you could use Array#map and return a new object with person property.
var object = { result: [{ name: "ABC", age: "20" }, { name: "DEF", age: "12" }] };
object.result = object.result.map(function (a) {
return { person: a };
});
console.log(object);

Rebuild nested array

I have an nested array that i want to rebuild based on age value:
//Data
data = {"people":
[{"male_1": [
{"name": "Bob" ,"age": "32"},
{"name":"Mike", "age":"31"}
]},
{"female_2": [
{"name":"Jessica", "age": "24"},
{"name":"Ann", "age": "23"}
]}
[{"male_3": [
{"name": "Tom" ,"age": "31"},
{"name":"John", "age":"29"}
]}, ...
]}
New array should looks like:
people = [{"male_1": [
{"name": "Bob" ,"age": "32"}
]},
[{"male_3": [
{"name": "Tom" ,"age": "31"}
]},
{"female_2": [
{"name":"Jessica", "age": "24"}
]}, ...
]}
Based on this example i need to find the largest age of all "persons" then add this person to array then do same with the next one. The age can be same in this case there is no difference who goes first.
With the next function i can find first one and push it to new array, but how find next one?
var age = 0;
data["people"].forEach(function(item) {
for (var key in item) {
if (item.hasOwnProperty(key)) {
item[key].forEach(function(person) {
if (person.age > age) {
age = person.age;
oldest_person = person
}
});
}
}
});
console.log(oldest_person);
here is another interpretation. This one uses the native Array.prototype.sort as the helper function.
var data = { "people": [{ "male_1": [{ "name": "Bob", "age": "32" }, { "name": "Mike", "age": "31" }] }, { "female_2": [{ "name": "Jessica", "age": "24" }, { "name": "Ann", "age": "23" }] }, { "male_3": [{ "name": "Tom", "age": "31" }, { "name": "John", "age": "29" }] }] },
oldies = [],
peopleByAge = data.people.map(function(group){
for( var name in group ){
group[name] = group[name].sort(sortBy('age'));
oldies.push( group[name][0] );
}
return group;
});
// sort by an object key
function sortBy( key ){
return function(a, b){
return parseInt(a[ key ]) < parseInt(b[ key ]);
}
}
document.write('<pre>' + JSON.stringify({ oldies: oldies.sort(sortBy('age')), peopleByAge: peopleByAge }, 0, 2) + '</pre>');
Try this:
var age = 0;
var oldest_person = [];
var data = {"people":
[
{"male_1": [
{"name": "Bob" ,"age": "32"},
{"name":"Mike", "age":"31"}
]},
{"female_2": [
{"name":"Jessica", "age": "24"},
{"name":"Ann", "age": "23"}
]},
{"male_3": [
{"name": "Tom" ,"age": "31"},
{"name":"John", "age":"29"}
]}
]};
data["people"].forEach(function(item) {
for (var key in item) {
if (item.hasOwnProperty(key)) {
var age = 0;
var name = key;
var oldest = null;
item[key].forEach(function(person) {
// Determine the oldest person in each group ("male_1", "female_2", "male_3", ...)
if (person.age > age) {
age = person.age;
oldest = person;
}
});
// Push the oldest person into the 'oldest_person' array
var group = {};
group[name] = [ oldest ];
oldest_person.push(group);
}
}
});
console.log(oldest_person);
You can use some Array methods, like Array.prototype.forEach(), Array.prototype.reduce() and Object.keys().
var data = { "people": [{ "male_1": [{ "name": "Bob", "age": "32" }, { "name": "Mike", "age": "31" }] }, { "female_2": [{ "name": "Jessica", "age": "24" }, { "name": "Ann", "age": "23" }] }, { "male_3": [{ "name": "Tom", "age": "31" }, { "name": "John", "age": "29" }] }] },
people = [];
data.people.forEach(function (a) {
Object.keys(a).forEach(function (k) {
var o = {};
o[k] = a[k].reduce(function (c, d) {
return c.age > d.age ? c : d;
});
people.push(o);
});
});
document.write('<pre>' + JSON.stringify(people, 0, 4) + '</pre>');

How to sort a multidimensional object in JavaScript [duplicate]

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

Categories

Resources