I have an array from which I want to get only names.
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
How can I get the name from each object with comma separation?
In jquery,
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
var names = new Array();
$.each(peoples,function(key,value){
names[key] = value.name;
});
namelist = names.join(",");
console.log(namelist);
http://jsfiddle.net/9344Q/
This will definitely do it in plain Javascript:
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
var arr = [];
peoples.forEach(function(name) {
arr.push(name['name']);
});
console.log(arr.join(','));
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
alert(peoples.map( function(v){ return v.name; }).join());
Related
const data=[{
"name": "Andrew",
"age": "23",
"subject": [{
"name": "english",
"period": "1st"
}]
},
{
"name": "karthick",
"age": "29",
"subject": [{
"name": "French",
"period": "3st"
}]
}]
I need to console only the name value in an array and print in console
Example:["Andrew","english","karthick","French"]
Using Array#flatMap and Array#map:
const data = [ { "name": "Andrew", "age": "23", "subject": [ { "name": "english", "period": "1st" } ] }, { "name": "karthick", "age": "29", "subject": [ { "name": "French", "period": "3st" } ] } ];
const res = data.flatMap(({ name, subject = [] }) => ([
name,
...subject.map(({ name }) => name)
]));
console.log(res);
Based on your example dataset you don't have to do anything complicated here. Loop over the data and then push the name and subject name into a new array.
const data=[{name:"Andrew",age:"23",subject:[{name:"english",period:"1st"}]},{name:"karthick",age:"29",subject:[{name:"French",period:"3st"}]}];
const arr = [];
for (const obj of data) {
arr.push(obj.name);
arr.push(obj.subject[0].name);
}
console.log(arr);
I have JSON like below, I need to filter out workers having the age less than 25.
var employee = {
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
I have tried to use the below code, but it returns all the value inside the workers array, but my expectation is it should return only the employee having than 25.
If I use Map function it is affecting the employee Object also.
var filteredResult = employee.filter(e => e.workers.some(w => w.age < 25))
Expected Result:
{
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
You can do it with a map and a filter, to avoid to modify the original array, you can use Object.asign
var employee = {
"value": [{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
var filteredResult = employee.value.map(e => {
let filter = e.workers.filter(w => w.age < 25)
return Object.assign({}, e, {workers: filter})
})
console.log('original', employee)
console.log('result', filteredResult)
You could reduce the array and check if the filtered workers have some elements then push a new object with changed workers to the result set.
var employee = { value: [{ position: "Seniro Developer", description: "Developemwnt", workers: [{ name: "Kumar", age: 22 }, { name: "aravinth", age: 29 }, { name: "sathish", age: 35 }] }, { position: "Tester", description: "testing", workers: [{ name: "vinth", age: 18 }, { name: "rahul", age: 45 }, { name: "sathish", age: 12 }] }] },
value = employee.value.reduce((r, o) => {
const workers = o.workers.filter(({ age }) => age < 25);
if (workers.length) r.push({ ...o, workers });
return r;
}, []),
result = { value };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can also try this:
var employee = { "value": [ { "position": "Seniro Developer", "description": "Developemwnt", "workers": [ { "name": "Kumar", "age": 22 }, { "name": "aravinth", "age": 29 }, { "name": "sathish", "age": 35 } ] }, { "position": "Tester", "description": "testing", "workers": [ { "name": "vinth", "age": 18 }, { "name": "rahul", "age": 45 }, { "name": "sathish", "age": 12 } ] } ]}
result = employee.value.map(({workers, ...rest})=>({...rest, workers:[...workers.filter(k=>k.age<25)]}));
console.log(result);
Use map and while creating the workers key in return object use filter to get employee with age less than 25. map will create an array
var employee = {
"value": [{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
let filteredEmployee = employee.value.map((item) => {
return {
"position": item.position,
"description": item.description,
"workers": item.workers.filter(elem => elem.age < 25)
}
});
let newObject = Object.assign({}, {
value: filteredEmployee
});
console.log(newObject)
You can use map method with ... rest syntax:
employee.value.map(({workers, ...rest}) => ({...rest,
workers: workers.filter(w => w.age < 25)}));
An example:
let employee = {
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
const result = employee.value.map(({workers, ...rest}) => ({...rest, workers: workers.filter(w => w.age < 25)}));
console.log(result);
I've been trying to transform some data using lodash without success. I am really new to javascript and lodash. How can I get the expected result?
I've used mapValues and chain, but I didn't achieve anything good.
const data = {
"north": [
{
"2018-07-01": {
"date": "2018-07-01",
"name": "david",
"age": 11
},
"2018-07-02": {
"date": "2018-07-02",
"name": "damo",
"age": 16
},
"2018-07-03": {
"date": "2018-07-03",
"name": "dani",
"age": 12
}
}
],
"south": [
{
"2018-07-01": [
{
"fruit": "banana",
"date": "2018-07-01",
"name": "miller",
"age": 11
},
{
"fruit": "mango",
"date": "2018-07-01",
"name": "mano",
"age": 11
},
{
"fruit": "avocado",
"date": "2018-07-01",
"name": "karl",
"age": 14
}
],
"2018-07-02": [
{
"fruit": "pineaplle",
"date": "2018-07-02",
"name": "gautier",
"age": 12
},
{
"fruit": "apple",
"date": "2018-07-02",
"name": "gauteng",
"age": 9
},
{
"fruit": "watermelon",
"date": "2018-07-02",
"name": "garzier",
"age": 12
}
]
}
]
};
Below is the expected result. I am trying to remove the dates which are outside the objects and arrays.
const expectedData = {
"north": [
{
"date": "2018-07-01",
"name": "david",
"age": 11
},
{
"date": "2018-07-02",
"name": "damo",
"age": 16
},
{
"date": "2018-07-03",
"name": "dani",
"age": 12
}
],
"south": [
{
"fruit": "banana",
"date": "2018-07-01",
"name": "miller",
"age": 11
},
{
"fruit": "mango",
"date": "2018-07-01",
"name": "mano",
"age": 11
},
{
"fruit": "avocado",
"date": "2018-07-01",
"name": "karl",
"age": 14
},
{
"fruit": "pineaplle",
"date": "2018-07-02",
"name": "gautier",
"age": 12
},
{
"fruit": "apple",
"date": "2018-07-02",
"name": "gauteng",
"age": 9
},
{
"fruit": "watermelon",
"date": "2018-07-02",
"name": "garzier",
"age": 12
}
]
};
You don't really need lodash for this. You can look at each key in your data and the just pull the values from each element of the array and concat it into a new array.
const data = {"north": [{"2018-07-01": {"date": "2018-07-01","name": "david","age": 11},"2018-07-02": {"date": "2018-07-02","name": "damo","age": 16},"2018-07-03": {"date": "2018-07-03","name": "dani","age": 12}}],"south": [{"2018-07-01": [{"fruit": "banana","date": "2018-07-01","name": "miller","age": 11},{"fruit": "mango","date": "2018-07-01","name": "mano","age": 11},{"fruit": "avocado","date": "2018-07-01","name": "karl","age": 14}],"2018-07-02": [{"fruit": "pineaplle","date": "2018-07-02","name": "gautier","age": 12},{"fruit": "apple","date": "2018-07-02","name": "gauteng","age": 9},{"fruit": "watermelon","date": "2018-07-02","name": "garzier","age": 12}]}]};
Object.keys(data).forEach(k => {
data[k] = data[k].reduce((a, c) => a.concat(...Object.values(c)), [])
})
console.log(data)
This starts with each key in your original object north and south. And for each one replaces the array with the accumulated values of each object in that array ignoring the keys.
alternatively you could just do this
const expectedData = {
north: Object.values(data.north[0]),
south: Object.values(data.south[0])
}
You can do any lodash quick operations, in pure JS way. But, since you tagged lodash
here is the version:
_.mapValues(data, v => _.flatMapDeep(v, _.values))
var data = {
"north": [
{
"2018-07-01": {
"date": "2018-07-01",
"name": "david",
"age": 11
},
"2018-07-02": {
"date": "2018-07-02",
"name": "damo",
"age": 16
},
"2018-07-03": {
"date": "2018-07-03",
"name": "dani",
"age": 12
}
}
],
"south": [
{
"2018-07-01": [
{
"fruit": "banana",
"date": "2018-07-01",
"name": "miller",
"age": 11
},
{
"fruit": "mango",
"date": "2018-07-01",
"name": "mano",
"age": 11
},
{
"fruit": "avocado",
"date": "2018-07-01",
"name": "karl",
"age": 14
}
],
"2018-07-02": [
{
"fruit": "pineaplle",
"date": "2018-07-02",
"name": "gautier",
"age": 12
},
{
"fruit": "apple",
"date": "2018-07-02",
"name": "gauteng",
"age": 9
},
{
"fruit": "watermelon",
"date": "2018-07-02",
"name": "garzier",
"age": 12
}
]
}
]
};
var expectedData = _.mapValues(data, v => _.flatMapDeep(v, _.values));
console.log(expectedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a json file like as below
[{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]
I want to convert to like this
[{
"id": 2,
"name": "Ali",
record: {
"type": "L",
"total": 123
}
},{
"id": 2,
"name": "Ali",
record: {
"type": "P",
"total": 102
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "O",
"total": 100
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "T",
"total": 88
}
}]
how can i do it using javascript?
Here is what you could do. However, this doesn't work in IE as is as Object.assign that is being used, isn't yet supported in IE. However, it could be replaced with any javascript object clone methods.
You could check : What is the most efficient way to deep clone an object in JavaScript?
var input = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}];
var output = [];
input.forEach((obj) => {
var records = obj.records;
delete obj.records;
records.forEach((record) => {
// Doesnt have any support in IE.
var newRecord = Object.assign({}, obj);
newRecord.record = record;
output.push(newRecord);
});
});
console.log(output);
If you are fine to use jQuery, here is what you could do.
var input = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}];
var output = [];
input.forEach((obj) => {
var records = obj.records;
delete obj.records;
records.forEach((record) => {
var newRecord = jQuery.extend({}, obj);
newRecord.record = record;
output.push(newRecord);
});
});
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a functional (but probably not very efficient) way of doing it:
function transform(data) {
// Merge the sub arrays together
return [].concat.apply([], (data.map(person => {
// Return an array of copied objects for each person
return person.records.map(record => {
// For each record, copy the person information
return {
id: person.id,
name: person.name,
record: record
};
});
})));
}
console.log(transform([{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]));
There's a few ways but Array.prototype.map seems to fit the bill. This blurb should get you started:
// We'll assume your original array is called myArray
var newArray = myArray.map ( function ( d ) {
return {
id : (d.id || 'theIDYouWant'),
name : (d.name || 'theNameYouWant' ),
record : { type : d.type, total : d.total }
}
} );
var jsonStr = JSON.stringify ( newArray );
console.log ( jsonStr ); // should write out your JSON as expected.
This will do it and save what you want in new_json
try running the code snippet below
json = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]
new_json = [];
for (var i = 0; i < json.length; i++) {
for (j = 0; j < json[i]['records'].length; j++) {
new_json.push({
id: json[i]['id'],
name: json[i]['name'],
record: json[i]['records'][j]
})
}
}
console.log(new_json);
I've never tried map/reduce.
How would I get the oldest of each type of animal?
My data is like this:
[
{
"cateory": "animal",
"type": "cat",
"age": 4,
"id": "a"
},
{
"cateory": "animal",
"type": "bird",
"age": 3,
"id": "b"
},
{
"cateory": "animal",
"type": "cat",
"age": 7
"id": "c"
},
{
"cateory": "animal",
"type": "bird",
"age": 4,
"id": "d"
},
{
"cateory": "animal",
"type": "cat",
"age": 8,
"id": "e"
},
{
"cateory": "company",
"type": "Internet",
"age": 5,
"id": "Facebook"
}
]
I'm using node-mongodb-native. Thanks!
Your map function should look something like this:
map = function() {
emit({type: this.type}, {age: this.age});
}
And the reduce function:
reduce = function(key, values) {
maxAge = 0;
values.forEach(function(v) {
if (maxAge < v['age']) {
maxAge = v['age'];
}
});
return {age: maxAge};
}
It's pretty simple:
collection.find({type : 'animal'}).sort({animal: -1}).limit(1);