how to change a value inside a array of obejcts - javascript

My array looks like,
[
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
]
I need to change the lat and lng to Lat and Long
What I tried,
coords[0].map((coord) => {
coord.replace("lat", "Lat");
coord.replace("lng", "long");
});

.map() is the right tool. But instead of thinking of this as modifying or replacing properties on each object, think of it has projecting the array into a new array. For example:
const myArr = [
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
];
const newArr = myArr.map(c => ({
Lat: c.lat,
Long: c.lng
}));
console.log(newArr);
So each iteration of .map() doesn't change the object, it creates a new object in whatever structure you like.

You can achieve this using the array map() function
const cords = [
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
]
const newCords = cords.map((cord) => ({Lat: cord.lat, Long: cord.lng}))
console.log(newCords);

In case you want to modify the original array as well.
coords.map(coord => {
let [lat, lng] = [coord.lat, coord.lng];
delete coord.lat;
delete coord.lng;
coord['Lat'] = lat;
coord['long'] = lng;
return coord;
});

This is one way of changing property names
let arr = [
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
]
arr.forEach(obj => {
Object.keys(obj).forEach(prop => {
if (prop === 'lng') {
obj["long"] = obj[prop];
delete obj[prop];
}
if (prop === 'lat') {
obj["Lat"] = obj[prop];
delete obj[prop];
}
});
});
console.log(arr)

A solution to update your original is as below
Logic
Loop through the array
Assign the value of lat from that object to Lat and lng to long in the same object
Delete lat and lng keys from the object
const cooordinates = [
{
"lat": 68.40928899869893,
"lng": 39.548560173006884
},
{
"lat": 45.35600542155823,
"lng": 32.5203664592608
},
{
"lat": 48.94054322456003,
"lng": 102.45089391103468
},
{
"lat": 70.14969277620159,
"lng": 96.8283389400378
}
]
cooordinates.forEach((node) => {
node['Lat'] = node['lat'];
node['long'] = node['lng'];
delete node['lat'];
delete node['lng'];
});
console.log(cooordinates);

Related

How to update an array of objects with data taken from the corresponding elements of another same-size array?

Say I have an array of objects as follows:
data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
]
and another array as follows:
myNumberArray = [1,2,3,4]
They might be much larger, but the number of elements in both arrays will always be the same. I want to modify each element of data by adding a number attribute, assigning it the value from the corresponding element of myNumberArray.
When done, data will look as follows:
data = [
{
"number":1,
"id":34
},
{
"number":2,
"id":35
},
{
"number":3,
"id":36
},
{
"number":4,
"id":37
}
]
How can I do this?
myNumberArray = [1,2,3,4]
data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
]
data.forEach((elem, index)=>{
data[index]["number"]=myNumberArray[index];
})
console.log(data);
This should solve your problem.
Explanation:
I used forEach to iterate over the data array, forEach accepts two parameters, the current value at an index, and the value.
Since, yours is a one-to-one mapping, we are using the current index to access the value at the same index in myNumberArray and assigning that new value in data for number key.
Try the following solution:
let myNumberArray = [1,2,3,4];
let data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
];
const updatedArray = data.map((item,index)=> {
return {
...item,
"number":myNumberArray[index]
}
});
console.log(updatedArray);
let myNumberArray = [1,2,3,4]
let data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
]
data = data.map( (x, i) => ({ number: myNumberArray[i], id: x.id}) )
console.log(data)
for (let i in myNumberArray) {
Object.assign(data[i], {
number: myNumberArray[i]
})
}

How to map this specific array of objects to the array grouped by the common key value

I have this simplified array of objects
var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"}, {"function":"function_2","process":"process_3"}, {"function":"function_2","process":"process_4"}]
that I want to map in JS according to the keys into the following array:
result = [
{
"function":"function_1",
"process": [
"process_1",
"process_2"
]
},
{
"function":"function_2",
"process": [
"process_3",
"process_4"
]
}
]
Dedicated to you my friend
var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"}, {"function":"function_2","process":"process_3"}, {"function":"function_2","process":"process_4"}]
var arr2 = items.reduce( (a,b) => {
var i = a.findIndex( x => x.function === b.function);
return i === -1 ? a.push({ function : b.function, process : [b.process] }) : a[i].process.push(b.process), a;
}, []);
console.log(arr2)
var items = [{
"function": "function_1",
"process": "process_1"
}, {
"function": "function_1",
"process": "process_2"
}, {
"function": "function_1",
"process": "process_3"
}, {
"function": "function_2",
"process": "process_3"
}, {
"function": "function_2",
"process": "process_4"
}]
var uniqueFunctionList = [] // to keep track of unique function names
var resultArr = []
items.forEach(item => {
if (!uniqueFunctionList.includes(item.function)) { // item object doesnt exist
uniqueFunctionList.push(item.function) // add unique function name
let tmp_obj = {}
tmp_obj['function'] = item.function // item is unique just push it
tmp_obj['process'] = [item.process] // make process array via []
resultArr.push(tmp_obj)
} else { // function name is not unique
resultArr.forEach(result => { // it is available in resultArr
if (result.function == item.function) { // find the function
result.process.push(item.process) // push to process array
}
})
}
})
console.log(resultArr)

JavaScript Array attribute change

I have an array like this.
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
I want to change it to like this
let me explain it a little. I want to assign the abbreviation directly to the name and the iterate through that array
let outout = [
{
"ISB":"ISLAMABAD"
},
{
"RAW":"ISLAMABAD"
},
{
"SWB":"SWABI"
},
{
"AQ":"AQEEL"
},
]
that is what I tried
let k = arr.map((item) => {
return item.ABB = item.name
})
console.log(k)
and here is the output
[ 'ISLAMABAD', 'PINDI', 'SWABI', 'AQEEL' ]
Here you go, use array map, simples
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
let outout = arr.map(({ABBRIVATION, name}) => ({[ABBRIVATION]: name}));
console.log(outout);
Nothing more than a simple Array.prototype.map() needed.
let arr = [
{
ABBRIVATION: "ISB",
name: "ISLAMABAD",
},
{
ABBRIVATION: "RAW",
name: "PINDI",
},
{
ABBRIVATION: "SWB",
name: "SWABI",
},
{
ABBRIVATION: "AQ",
name: "AQEEL",
},
];
const result = arr.map(e => ({ [e.ABBRIVATION]: e.name }));
console.log(result);
map over the array of objects (map returns a new array) and assign the name to a new key defined by the abbreviation.
You code works the way it does because item.ABB is undefined, but you're also assigning item.name to it which does get returned, so you just get an array of names returned.
const arr=[{ABBRIVATION:"ISB",name:"ISLAMABAD"},{ABBRIVATION:"RAW",name:"PINDI"},{ABBRIVATION:"SWB",name:"SWABI"},{ABBRIVATION:"AQ",name:"AQEEL"}];
const out = arr.map(obj => {
return { [obj.ABBRIVATION]: obj.name };
});
console.log(out);
Hi I have seen people answer, but most of them use the map function, I provide some other solutions, hoping to expand the thinking
Use forEach function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
datas.forEach((obj, i, arr) => {
const{'ABBRIVATION':k, 'name':v} = obj;
arr[i] = {[k]:v};
});
console.log(datas);
Use flatMap function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
const result = datas.flatMap(obj => {
const {'ABBRIVATION':k, 'name':v} = obj;
return {[k]:v};
});
console.log(result);
this is how you suppose to do it.
arr.reduce((d, c)=>([...d, {[c.ABBRIVATION]: c.name}]),[])
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
console.log(arr.reduce((data, current)=>([...data, {[current.ABBRIVATION]: current.name}]),[]))

filtering deep nested objects array using lodash not working correctly

I have product structure as shown below:
product = {
"name":"MyXam",
"layers":[
{
"countries":[
{
"countryId":"1",
"countryName":"ABC"
},
{
"countryId":"2",
"countryName":"XYZ"
},
{
"countryId":"3",
"countryName":"PQR"
}
]
},
{
"countries":[
{
"countryId":"5",
"countryName":"LMN"
},
{
"countryId":"3",
"countryName":"PQR"
}
]
}
]
}
And selected countries:
selCountries = [
{
"countryId":"1"
},
{
"countryId":"3"
}
]
Now I want to filter the product in such a way that it should contain countries only that are in selCountries.
The final product should be:
{
"name":"MyXam",
"layers":[
{
"countries":[
{
"countryId":"1",
"countryName":"ABC"
},
{
"countryId":"3",
"countryName":"PQR"
}
]
},
{
"countries":[
{
"countryId":"3",
"countryName":"PQR"
}
]
}
]
}
I have tried the following using lodash but is not working:
_.filter(product.layers, _.flow(
_.property('countries'),
_.partialRight(_.some, selCountries)
));
As the product comes dynamically in my application. In some cases there is a possibility that some of the layers may have not countries. So the solution should handle this case also and should not break with undefined error.
Can any on help me, where I am going wrong?
You should not need lodash for that. Just filter based on ID. If for all layers, map/forEach on the layers and filter the countries.
const product = {
"name":"MyXam",
"layers":[
{
"countries":[
{
"countryId":"1",
"countryName":"ABC"
},
{
"countryId":"2",
"countryName":"XYZ"
},
{
"countryId":"3",
"countryName":"PQR"
}
]
}
]
}
const selCountries = [
{
"countryId":"1"
},
{
"countryId":"3"
}
];
const indices = selCountries.map(e => e.countryId); // Just IDs plz.
product.layers.forEach(layer => {
if (layer.countries == null)
return;
layer.countries = layer.countries.filter(e =>
indices.some(i => i == e.countryId)
);
});
console.log(product);
My answer's similar to 31piy's in that I extract out the ids from selCountries first, and then rebuild the object with the filtered results. It also checks whether there are countries in the layers array as per your recent comment.
product = {"name":"MyXam","layers":[{"countries":[{"countryId":"1","countryName":"ABC"},{"countryId":"2","countryName":"XYZ"},{"countryId":"3","countryName":"PQR"}]},{"countries":[{"countryId":"5","countryName":"LMN"},{"countryId":"3","countryName":"PQR"}]}]}
const selCountries=[{"countryId":"1"},{"countryId":"3"}];
if (product.layers.length) {
const selCountriesArr = selCountries.map(el => el.countryId);
const newLayers = product.layers.map(obj => {
const countries = obj.countries.filter(el => selCountriesArr.includes(el.countryId));
return { countries };
});
const filteredProduct = { ...product, layers: newLayers };
console.log(filteredProduct);
}
You can create a temporary array with the IDs of countries selected, and then filter the countries based on it. Note that it modifies the original object in-place.
let product = {
"name": "MyXam",
"layers": [{
"countries": [{
"countryId": "1",
"countryName": "ABC"
},
{
"countryId": "2",
"countryName": "XYZ"
},
{
"countryId": "3",
"countryName": "PQR"
}
]
}]
};
let selCountries = [{
"countryId": "1"
},
{
"countryId": "3"
}
];
// Extract the IDs
let selCountryIds = _.map(selCountries, 'countryId');
// Filter the countries based on IDs
product.layers[0].countries = _.filter(product.layers[0].countries, country => {
return _.includes(selCountryIds, country.countryId);
});
console.log(product);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
Instead of using lodash, you can make use of Array.map and Array.filter to iterate through the array and filter the product as per the selected countries.
var product = {
"name":"MyXam",
"layers":[
{
"countries":[
{
"countryId":"1",
"countryName":"ABC"
},
{
"countryId":"2",
"countryName":"XYZ"
},
{
"countryId":"3",
"countryName":"PQR"
}
]
}
]
}
var selCountries = [
{
"countryId":"1"
},
{
"countryId":"3"
}
];
product.layers = product.layers.map(function (layer) {
return layer.countries.filter(function (country) {
return selCountries.some(function(selCountry) {
return selCountry.countryId === country.countryId;
});
});
});
console.log(product);

lodash - object transformation

Data Source
var data = {
"2017-08-09": [
{
"time": "09:00",
"available": true
},
{
"time": "13:00",
"available": true
},
{
"time": "13:30",
"available": true
},
]
}
Desired Transformation
newData = [ "2017-08-09": ['09:00','13:00','13:30'] ]
I have tried the following:
function recursiveFunction(collection){
var newData = [];
_.forOwn(collection, function(value, key){
newData.push( {key});
value.map( item => {
if (item.available === true) newData.key = item.time
})
});
console.log(newData)
};
But not quite there :/
http://jsfiddle.net/oa6nbgpy/
Map across the values using mapValues, filter only the available times and pluck the time using map:
var newData = _.mapValues(data, times => _.map(_.filter(times, 'available'), 'time'));
With vanilla JS, use Object#keys to get an array of keys, and convert them to objects using Array#map, Array#filter and computed property names:
var data = {"2017-08-09":[{"time":"09:00","available":true},{"time":"09:30","available":false},{"time":"11:30","available":true}],"2017-08-10":[{"time":"10:00","available":true},{"time":"10:30","available":false}]};
var result = Object.keys(data).map(function(key) {
return {
[key]: data[key]
.filter(function(o) {
return o.available;
})
.map(function(o) {
return o.time;
})
};
});
console.log(result);

Categories

Resources