Map functions in javascript - javascript

var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
var finalData = data.map(x => {
return ({ cno: x.cno + 1 })
});
console.log(finalData); // output [ { cno: 2} ]
My expected output i need this as object not as Array, is it possible to do using map?
Finally i need { cno : 2}

Since you're just trying to operate on a single object you shouldn't use map at all. You should use something like:
var finalData = { cno: data[ 0 ].cno + 1 };
Example:
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
var finalData = { cno: data[ 0 ].cno + 1 };
console.log( finalData );

you can use reduce instead of map. map actually return an array. using reduce you can get the desired result.
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
var finalData = data.reduce((acc, elem, index) => {
acc.cno = elem.cno + 1
return acc
}, {});
console.log(finalData); // output { cno: 2}

The simplest approach is using ES6 destructuring ([data] = data;) as in the following example:
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
[data] = data; // data is now the nested object
console.log(data); // Return data as object
// After that, you can modify data however you want
data.cno += 1;
console.log(data); // Return updated data as object

Related

Filter multiple array object with multiple property

Im trying to create a filter function where it can return a result of data that matches the value that i am looking for , from the given set of string keys
example of array:
let data = [
{ id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
{ id:2 , data:{ name:"sample2",address:{ cat:"office" } } },
{ id:3 , data:{ name:"sample3",address:{ cat:"office" } } },
{ id:4 , data:{ name:"sample4",address:{ cat:"office" } } }
{ id:5 , data:{ name:"sample5",address:{ cat:"home" } } }
{ id:6 , data:{ name:"sample6",address:{ cat:"home" } } }
]
function filter( collection , value ,key ){
//code
}
let result = filter( data , "business" , [ "data","address","cat" ] )
console.log(result)
expected result is
{ id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
You can use filter to search for the data. Use reduce to construct the keys.
Note: filter returns an array of matched elements. If you prefer the first match only, you can use find
const data = [
{ id: 1, data: { name: "sample1", address:{ cat: "business" } } },
{ id: 2, data: { name: "sample2", address:{ cat: "office" } } },
{ id: 3, data: { name: "sample3", address:{ cat: "office" } } },
{ id: 4, data: { name: "sample4", address:{ cat: "office" } } },
{ id: 5, data: { name: "sample5", address:{ cat: "home" } } },
{ id: 6, data: { name: "sample6", address:{ cat: "home" } } }
]
const filter = (collection, keys, value) =>
collection.filter(o => keys.reduce((c, v) => c[v] || {}, o) === value)
const result = filter(data, ["data", "address", "cat"], "business")
console.log(result)
function filter( collection , value ,key ){
const getNestedObjectValue = (nestedObject, propertyPath) => {
return propertyPath.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObject);
};
return collection.filter( item => getNestedObjectValue(item, key) === value);
}
The filter function will return an array of matching object(s) when there is a match and an empty array when there is no match
let result = filter( data , "business" , [ "data","address","cat" ] );
console.log(result); // [{"id":1,"data":{"name":"sample1","address":{"cat":"business"}}}]
let result2 = filter( data , "office" , [ "data","address","cat" ] );
console.log(result2); //[{"id":2,"data":{"name":"sample2","address":{"cat":"office"}}},{"id":3,"data":{"name":"sample3","address":{"cat":"office"}}},{"id":4,"data":{"name":"sample4","address":{"cat":"office"}}}]
let result3 = filter( data , "vacation" , [ "data","address","cat" ] );
console.log(result2); // []
You can try below code.
Please comment if it doesn't satisfy your problem or if you want more functionality to be added in the code. I will update my answer.
function filter( collection , value ,key ){
for(var obj of collection) {
if(obj[key[0]][key[1]][key[2]] == value)
{
return obj
}
}
return null;
}
Clean code using Underscore and ES6 arrow notation.
const equalTo = expected => actual => expected === actual;
function filterDeepValue(collection, value, path) {
const criterion = _.compose(equalTo(value), _.property(path));
return _.filter(collection, criterion);
}
const data = [
{id: 1, data: {name: "sample1", address: {cat: "business"}}},
{id: 2, data: {name: "sample2", address: {cat: "office"}}},
{id: 3, data: {name: "sample3", address: {cat: "office"}}},
{id: 4, data: {name: "sample4", address: {cat: "office"}}},
{id: 5, data: {name: "sample5", address: {cat: "home"}}},
{id: 6, data: {name: "sample6", address: {cat: "home"}}},
];
console.log(filterDeepValue(data, 'business', ['data', 'address', 'cat']));
<script src="https://underscorejs.org/underscore-umd-min.js"></script>

Conversion of arrays using map or any other methods - javascript

This is my json object:
{
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
I want my expected output like this:
[
{id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:5},
{id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:1}
]
You are right to choose .map. Issue is, you are trying to update an object and objects are passed using reference. So all the objects will hold same id. You will have to create a copy so that you do not override value. You can use Object.assign for that.
var data = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
};
var result = data.storeId.map(function(id){
return Object.assign({}, data, {storeId: id});
});
console.log(result)
If you are not comfortable using ES6 features, you can check following: How do I correctly clone a JavaScript object?
You can use .map() on the array storeId and return a new object which has current value as the value of storeId.
var obj = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
};
var data = obj.storeId.map(el => {
let newObject = Object.assign({}, obj);
newObject.storeId = el;
return newObject;
})
console.log(data);
You can use array#map with spread syntax to create an object with all the existing property and individual storeId.
var obj = {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId: [ 5, 1 ]}
result = obj.storeId.map(storeId => ({...obj, storeId}) )
console.log(result);
var data = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
var finalData = data.storeId.map(x => {
return({
id: data.id,
cno: data.cno,
username: data.username,
name: data.name,
desc: data.desc,
storeId: x
})
});
console.log(finalData);
I tried this now i got this answer correctly, is this good approach?

Build new array of objects with array containing unique data from array of objects with duplicate values of specific keys

I need your help...
I got an Array of Objects looking something like this:
var arr = [{
title: 'My title',
user: 1,
price: 22,
location: 'Berlin'
},{
title: 'My title',
user: 1,
price: 18,
location: 'Cologne'
},{
title: 'My title',
user: 1,
price: 26,
location: 'Hamburg'
},{
title: 'Other Title',
user: 2,
price: 26,
location: 'Frankfurt'
},{
title: 'Other Title',
user: 2,
price: 28,
location: 'Munich'
},];
Now I want to build a new Array of Objects that will look like this:
var result = [{
title: 'My title',
user: 1,
events: [
{
price: 22,
location: 'Berlin'
}, {
price: 18,
location: 'Cologne'
}, {
price: 26,
location: 'Hamburg'
}
]
},{
title: 'Other Title',
user: 2,
events: [
{
price: 28,
location: 'Munich'
},{
price: 26,
location: 'Frankfurt'
}
]
}];
I need to group the objects by multiple values, like in my example by user and title and add the unique data of them to a new field.
If someone could show me how to do that with lodash would be awesome!
Thank you for your help!
arr.reduce(function (hash, item) {
var key = item.title + item.user;
var obj = hash[key] || {};
obj.title = item.title;
obj.user = item.user;
obj.events = obj.events || [];
obj.events.push({
price: item.price,
location: item.location
});
hash[key] = obj;
return hash;
}, {});
var result = [];
for (var key in arr) {
result.push(arr[key]);
}
console.log(result); // the result array
Lodash answer:
function remap(arr) {
var out = _.reduce(arr, function(p, c) {
var key = [c.user, c.title].join('|');
p[key] = p[key] || { title: c.title, user: c.user, events: [] };
p[key].events.push({ price: c.price, location: c.location });
return p;
}, {});
return _.map(_.keys(out), function(el) {
return out[el];
});
}
remap(arr);
DEMO
This is a proposal in plain Javascript with a temporary object for the references to the result array.
var arr = [{ title: 'My title', user: 1, price: 22, location: 'Berlin' }, { title: 'My title', user: 1, price: 18, location: 'Cologne' }, { title: 'My title', user: 1, price: 26, location: 'Hamburg' }, { title: 'Other Title', user: 2, price: 26, location: 'Frankfurt' }, { title: 'Other Title', user: 2, price: 28, location: 'Munich' }],
grouped = function (array) {
var r = [], o = {};
array.forEach(function (a) {
if (!o[a.user]) {
o[a.user] = { title: a.title, user: a.user, events: [] };
r.push(o[a.user]);
}
o[a.user].events.push({ price: a.price, location: a.location });
});
return r;
}(arr);
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

Creating new javascript Object form existing one

I have my original objects as follow. All I need is to just extract few properties from existing one and create new object.
var data = [{
id: 3,
name: Axe,
location: alkt
}, {
id: 5,
name: Roy,
location: grelad
}]
I need my output as,
var data_new = [{
id: 3,
name: Axe
}, {
id: 5,
name: Roy,
}]
How to implement in underscore js or any simple method. Possible its a large JSON object.
If there are just few properties you want to extract then simple Array.prototype.map will works fine:
var data = [{
id: 3,
name: 'Axe',
location: 'alkt'
}, {
id: 5,
name: 'Roy',
location: 'grelad'
}]
var result = data.map(function(obj) {
return {
id: obj.id,
name: obj.name
};
});
alert(JSON.stringify(result, null, 4));
Use pick in undescorejs http://underscorejs.org/#pick
Or omit http://underscorejs.org/#omit
_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
return _.isNumber(value);
});
=> {age: 50}
It you want remove each item's location
var data_new = _.map(data, function(item) {
return _.omit(item, 'location');
});
If all you want is remove properties from objects in an array, you could just delete them while iterating with forEach:
var data_new = data;
data_new.forEach(function(obj){ delete obj.location; /* or any other */ });
$scope.data_new = [];
for(i in $scope.data){
$scope.data_new.push(
{ id: $scope.data[i].id, name: $scope.data[i].name }
)
}

Push data on array with two levels

Does anybody knows or give me some directions on how to populate a multidimensional data array:
I have one data array with this:
dataTable = [
{section: 'section1', item: 'item1', num: 0},
{section: 'section2', item: 'item1', num: 0},
{section: 'section3', item: 'item1', num: 0},
{section: 'section3', item: 'item2', num: 0}
];
I need to populate that 2D array with this data on the following format:
tableToLoad = [{
sectionNum: 1,
sectionTitle: "section1",
data: [{
level: 1,
title: item1,
child: false
}]
}, {
sectionNum: 2,
sectionTitle: "section2",
data: [{
level: 1,
title: item1,
child: false
}]
}, {
sectionNum: 3,
sectionTitle: "section3",
data: [{
level: 1,
title: item1,
child: false
}, {
level: 1,
title: item2,
child: false
}]
}];
Thanks in advance...
var tableToLoad = [], tableSecIdx = {};
dataTable.forEach(function(item) {
//find the sec index
var idx = tableSecIdx[item.section];
if (!idx) {
//push a new one
tableToLoad.push({
sectionNum : tableToLoad.length + 1,
sectionTitle : item.section,
data : []
});
//remember the idx
tableSecIdx[item.section] = idx = tableToLoad.length - 1;
}
//push the data
tableToLoad[idx].data.push({
level : 1,
title : item.item,
child : false
});
});
http://jsfiddle.net/8Zke8/2/
try following way:
var tableToLoad = [], dataMap = {};
for (var i = 0; i < dataTable.length; i++) {
var data = dataTable[i];
if (dataMap[data.section]) {
dataMap[data.section].data.push({
level: 1,
title: data.item,
child: false
});
continue;
}
var newData = {
sectionNum: tableToLoad.length + 1,
sectionTitle: data.section,
data: [{
level: 1,
title: data.item,
child: false
}]
};
dataMap[data.section] = newData;
tableToLoad.push(newData);
}

Categories