Convert some fields of array of objects to json data in javascript? - javascript

I have an array of objects as mentioned below,
var arraydata =[
{ id:1, name:"Abraham", age:20,gender:"male"},
{ id:2, name:"Annie", age:25,gender:"female"},
{ id:3, name:"Ryan", age:40,gender:"male"},
{ id:4, name:"Wayne", age:31,gender:"male"},
{ id:5, name:"Paul", age:45,gender:"male"}
];
how to convert this to a JSON data, which has only "id" and "name" field?

syntax is wrong age=20,gender="male" change it to age:20,gender:"male"
var arraydata =[
{ id:1, name:"Abraham", age: 20, gender:"male"},
{ id:2, name:"Annie", age: 25, gender:"female"},
{ id:3, name:"Ryan", age: 28, gender:"male"},
{ id:4, name:"Wayne", age: 19, gender:"male"},
{ id:5, name:"Paul", age: 45,gender:"male"}
];
var ans= arraydata.map(function(a){
return {id:a.id,name:a.name};
})
console.log(ans);

You can use the delete operator which remove a property from an object.
var arraydata = [{
id: 1,
name: "Abraham",
age : 20,
gender : "male"
}, {
id: 2,
name: "Annie",
age : 25,
gender : "female"
}, {
id: 3,
name: "Ryan",
age : 40,
gender : "male"
}, {
id: 4,
name: "Wayne",
age : 31,
gender : "male"
}, {
id: 5,
name: "Paul",
age : 45,
gender : "male"
}];
arraydata.forEach(function(item){ delete item.age; delete item.gender });
console.log(arraydata);

var arraydata =[
{ id:1, name:"Abraham", age: 20, gender: "male"},
{ id:2, name:"Annie", age: 25, gender: "female"},
{ id:3, name:"Ryan", age: 28, gender: "male"},
{ id:4, name:"Wayne", age: 19, gender: "male"},
{ id:5, name:"Paul", age: 45, gender: "male"}
];
var _ = arraydata.map(function(item) {
return { id: item.id, name: item.name };
});
var jsonData = JSON.stringify(_);
console.log(jsonData);
You can of course chain together the two steps.
Fiddle

Related

How do I extract duplicate values for objects in JavaScript?

I have the data from the database and I want to push the duplicate value to each array. I attach the exact example I want.
// origin data
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
//result that I want to get
arr1 = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
];
arr2 = [
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
I want to create an array based on the name in this data and push it. Can anyone help?
One way would be to use reduce together with Object.values:
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
}
];
const result = Object.values(data.reduce((acc, cur) => {
const key = `${cur.name}:${cur.age}`;
const prev = acc[key] || [];
return {
...acc,
[key]: prev.concat(cur)
}
}, {}));
console.log(result);

JavaScript sort an array of objects based array of properties

I have for example this dataset:
const order = [
{ key: "job", direction: "ascending" },
{ key: "age", direction: "descending" },
];
const records = [
{ name: "christian", age: 40, job: "developer" },
{ name: "andrew", age: 48, job: "developer" },
{ name: "elisabeth", age: 31, job: "floor manager" },
{ name: "oscar", age: 61, job: "floor manager" },
{ name: "gisela", age: 51, job: "area manager" },
{ name: "buffy", age: 27, job: "trainee" },
{ name: "carl", age: 23, job: "trainee" },
];
I need to sort the records array according to the criteria from order array.
I ended up with this solution:
const sorted = records.sort(
(recordA, recordB) =>
recordA.job.localeCompare(recordB.job) || recordA.age - recordB.age
);
But I cant understand how can I use the order array instead of hardcoded the job and age properties. The order array can have many properties.
You could take a closure over the wanted order and check the value if finite then return the delta or treat the values as string.
Inside sorting function iterate as long as the return value is falsy and take this value as return value for sorting.
const
sortBy = order => (a, b) => {
let r;
order.some(({ key, direction }) => r = (isFinite(a[key]) && isFinite(b[key])
? a[key] - b[key]
: a[key].toString().localeCompare(b[key])
) * (direction === 'ascending' || -1))
return r;
},
records = [{ name: "christian", age: 40, job: "developer" }, { name: "andrew", age: 48, job: "developer" }, { name: "elisabeth", age: 31, job: "floor manager" }, { name: "oscar", age: 61, job: "floor manager" }, { name: "gisela", age: 51, job: "area manager" }, { name: "buffy", age: 27, job: "trainee" }, { name: "carl", age: 23, job: "trainee" }],
order = [{ key: "job", direction: "ascending" }, { key: "age", direction: "descending" }];
console.log(records.sort(sortBy(order)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just loop over the order data and make the comparisons:
let order = [{ key: "job", direction: "ascending" }, { key: "age", direction: "descending" }];
let records = [{ name: "christian", age: 40, job: "developer" }, { name: "andrew", age: 48, job: "developer" }, { name: "elisabeth", age: 31, job: "floor manager" }, { name: "oscar", age: 61, job: "floor manager" }, { name: "gisela", age: 51, job: "area manager" }, { name: "buffy", age: 27, job: "trainee" }, { name: "carl", age: 23, job: "trainee" }];
records.sort(function (a, b) {
for (let {key, direction} of order) {
if (a[key] !== b[key]) return (direction[0] === "a") === (a[key] < b[key]) ? -1 : 1;
}
return 0;
});
console.log(records);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use (a[key] > b[key]) - (a[key] < b[key]) to compare two values either lexically or numerically (if both are numbers). This could then be used like:
const order = [
{ key: "job", direction: "ascending" },
{ key: "age", direction: "descending" },
];
const records = [
{ name: "christian", age: 40, job: "developer" },
{ name: "andrew", age: 48, job: "developer" },
{ name: "elisabeth", age: 31, job: "floor manager" },
{ name: "oscar", age: 61, job: "floor manager" },
{ name: "gisela", age: 51, job: "area manager" },
{ name: "buffy", age: 27, job: "trainee" },
{ name: "carl", age: 23, job: "trainee" },
];
const compare = (key) => (a, b) => (a[key] > b[key]) - (a[key] < b[key]);
const or = (a, b) => (...v) => a(...v) || b(...v);
const sorter = order.map(it => compare(it.key)).reduce(or);
const sorted = records.sort(sorter);
console.log(sorted);
The implementation of direction was left to the reader

How to convert one field in a multidimensional array to lowercase?

For example if I have a multidimensional array like this:
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" },
];
and I want to create a function to turn one field in this array (ex: state) to lowercase, how would I go about doing so?
I have tried this:
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" },
];
function lowerCaseStates(coWorkers.resident_state){
lowerCasing = function() {
return coWorkers.resident_state.toLowerCase();
}
lowercaseStates = coWorkers.map(lowerCasing);
console.log(lowercaseStates)
}
lowerCaseStates()
How would I go about doing this while not replacing each cell in the array individually?
You cannot have a dotted parameter in the function (and do not need it if you access it inside the function
just run directly on the string
You do not have a multidimensional array. You have an object array
You can use a function to process the complete array in one map statement - I use the ...rest to just copy the other items we are not interested in
Note I have to wrap the object in () if I do not have => {} in the arrow function
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" }
];
const lowerCase = ({resident_state, ...rest }) =>
({ resident_state: resident_state.toLowerCase(), ...rest });
const coWorkersLowerCase = coWorkers
.map(lowerCase)
console.log(coWorkersLowerCase)
If you want to modify the original, you can use a forEach
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" }
];
coWorkers.forEach(item => item.resident_state = item.resident_state.toLowerCase())
console.log(coWorkers)
Hi i would go like this
coWorkers.map(x=>{
x.resident_state=x.resident_state.toLowerCase();
return x
})

How to merge the property with same key in two object array?

There are two object array, some of them have the same key, I'd like to merge the same key in the first array. I have pasted my code.I used nested loop, but the performance was bad O(n²). Maybe I need another method to enhance performance.(I can't use ES6 for some reason, so I'll appreciate if it is the ES5 method.)
var people = [
{
id: "001",
name: "David",
age: 29
},
{
id: "002",
name: "Lucia",
age: 41
},
{
id: "003",
name: "Steve",
age: 18
}
];
var address = [
{
id: "001",
city: "Barcelona"
},
{
id: "002",
city: "Paris"
},
{
},
{
id: "003",
city: "Tokyo"
},
{
id: "004",
city: "Barcelona"
}
];
My code
people.forEach(function(item) {
var id = item.id;
address.forEach(function(location) {
if (location.id == id) {
item.address = location.address
}
});
});
Result
var people = [
{
id: "001",
name: "David",
age: 29,
city: "Barcelona"
},
{
id: "002",
name: "Lucia",
age: 41,
city: "Paris"
},
{
id: "003",
name: "Steve",
age: 18,
city: "Tokyo"
}
];
The new people array is I preferred.
You could take a Map with all addresses and then map new object with extended properties of the map.
This approach takes all properties of address objects.
var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }],
map = new Map(address.map(o => [o.id, o])),
result = people.map(o => Object.assign({}, o, map.get(o.id)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Make a Map with cities by id, and use it when iterating over the people array to find out the city:
let cities = new Map(address.map(a => [a.id, a.city]));
let people2 = people.map(p => ( {...p, city: cities.get(p.id)} ));
You could use Array#map to iterate over people, and Array#find to find the corresponding address from id within iterations:
const people = [{id: "001",name: "David",age: 29 },{ id: "002", name: "Lucia", age: 41
},{ id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" },{ id: "002", city: "Paris" },{ },{ id: "003", city: "Tokyo" },{ id: "004", city: "Barcelona" }];
console.log(
people.map(p => ({
...p,
...address.find(a => (p.id === a.id))
}))
);
However, that's supposing that the properties' name of address's items are not the same as people's ones.
The code below is not tested but it should work
// create an object to store them
const mergedItems = {};
// merge the 2 arrays so you only map them once (just for shorter code)
people.concat(address).map(entity => {
// add each entity on the object and id as a key
mergedItems[entity.id] = {
// if the key exist, it will merge it with the new entity
...mergedItems[entity.id],
...entity,
}
)
// this is your merged items
// Object.values will convert it from object to array
const finalItems = Object.values(mergedItems);
I used map instead of for loop because it is faster: https://codeburst.io/javascript-map-vs-foreach-f38111822c0f
I have used Object.assign method to add values from address
var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }];
people.forEach(function(item,pos){
Object.assign(item,{},address[address.findIndex(o=>o.id == item.id)]);
});
console.log(people);

How to remove "integer" array from object in JavaScript

I got this input
var input=[ "Axel",
4,
4.21,
{ name : 'Bob', age : 16 },
{ type : 'fish', model : 'golden fish' },
[1,2,3],
"John",
{ name : 'Peter', height: 1.90} ];
and the Result must be this one
[ { name : 'Bob', age : 16 },
{ type : 'fish', model : 'golden fish' },
{ name : 'Peter', height: 1.90} ];
Using Array.prototype.filter, only keep Objects which are not Arrays
var input = ["Axel",
4,
4.21,
{name: 'Bob', age: 16},
{type: 'fish', model: 'golden fish'},
[1, 2, 3],
"John",
{name: 'Peter', height: 1.90}
];
input = input.filter(function (e) {
return (typeof e === 'object') && !Array.isArray(e);
}); /*
[
{"name": "Bob", "age": 16},
{"type": "fish", "model": "golden fish"},
{"name": "Peter", "height": 1.9}
]
*/
Try using array filter to remove the unwanted elements.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
To remove all integers
var filteredList = input.filter(function(val) {
return isNaN(val);
}):
/*
filteredList is now =
{ name: 'Bob', age: 16 },
{ type: 'fish', model: 'golden fish' },
[ 1, 2, 3 ],
'John',
{ name: 'Peter', height: 1.9 } ]
*/

Categories

Resources