I have an array of cities with this structure (given from the CMS):
const cities = [
{
city: 'Genova',
coordinates: '{\'type\':\'Point\',\'coordinates\':[8.9473343,44.4023918]}',
countryIsoCode: 'it',
description: 'test',
isInitialCity: true,
}, {
city: 'Barcelona',
coordinates: '{\'type\':\'Point\',\'coordinates\':[2.0951271,41.3397004]}',
countryIsoCode: 'es',
description: 'description',
isInitialCity: false,
}, {
city: 'Sydney',
coordinates: '{type\':\'Point\',\'coordinates\':[151.2158203,-33.8704156]}',
countryIsoCode: 'au',
description: 'Sydney description',
isInitialCity: false,
}];
I want to parse the coordinates position to get a more scalable object and get its properties nesting.
This is what I've tried:
cities.map(city=>JSON.parse(city.coordinates))
But when I print it seems to have no effect. However, if I manually print a position like console.log(JSON.parse(cities[0].coordinates)) it shows a formatted result like is shown in the following screenshot:
How can I make it automatically via loop?
This is what I've tried:
cities.map(city=>JSON.parse(city.coordinates))
map() created you a brand new, separate array with the coordinates only, which you have thrown away afterwards.
However, if I manually print a position like console.log(JSON.parse(cities[0].coordinates)) [...] How can I make it automatically via loop?
Well, put it in a loop:
for(let city of cities)
city.coordinates = JSON.parse(city.coordinates);
However your example data is syntactically incorrect, there are ,}-s at the end of the objects (after the true/false), and the supposed JSON data is not JSON, like
{type':'Point','coordinates':[151.2158203,-33.8704156]}
^it has no pair, and it should be double quote anyway, all of them
{"type":"Point","coordinates":[151.2158203,-33.8704156]} <-- this is JSON
What I think might be happening is that you're doing the map right but not returning the result.
For example mynumbers.map(num => num++) won't actually effect mynumbers at all. You have to assign the result of the map to another variable...
const parsedCities = cities.map(city=>JSON.parse(city.coordinates))
Now your new parsedCities variable will look like you want it to and the original cities array will remain unchanged.
const cities = [
{
city: 'Genova',
coordinates: '{\'type\':\'Point\',\'coordinates\':[8.9473343,44.4023918]}',
countryIsoCode: 'it',
description: 'test',
isInitialCity: true,
}, {
city: 'Barcelona',
coordinates: '{\'type\':\'Point\',\'coordinates\':[2.0951271,41.3397004]}',
countryIsoCode: 'es',
description: 'description',
isInitialCity: false,
}, {
city: 'Sydney',
coordinates: '{type\':\'Point\',\'coordinates\':[151.2158203,-33.8704156]}',
countryIsoCode: 'au',
description: 'Sydney description',
isInitialCity: false,
}];
//for(let city of cities)
// city.coordinates = JSON.parse(city.coordinates);
var x=cities.map(city=>JSON.parse(JSON.stringify(city.coordinates)))
console.log("result :"+(JSON.stringify(x)))
// result :["{'type':'Point','coordinates':[8.9473343,44.4023918]}","{'type':'Point','coordinates':[2.0951271,41.3397004]}","{type':'Point','coordinates':[151.2158203,-33.8704156]}"]
Related
I am wondering what js functions can be used in the following case to get some array values together.
Here I want to concatenate the description values if the date value is null.
var incomes = [ { date: '05/03', description: '1st Description on 05/03', amount: '399.49' },
{ date: null, description: '1st Description continued on 05/03', amount: null },
{ date: null, description: '1st Description continued on 05/03', amount: null },
{ date: '05/03', description: '2nd Description on 05/03', amount: '269.85' },
{ date: null, description: '2nd Description continued on 05/03', amount: null },
{ date: null, description: '2nd Description continued on 05/03', amount: null }];
The result should look like this:
var results = [ { date: '05/03',
description: '1st Description on 05/03, 1st Description continued on 05/03, 1st Description continued on 05/03',
amount: '399.49' },
{ date: '05/03',
description: '2nd Description on 05/03, 2nd Description continued on 05/03, 2nd Description continued on 05/03',
amount: '269.85' }];
I think that we can use the usual loops, conditions, etc. But are there any handy method to solve this?
This really isn't a good use case for reduce/concat types of operations. Reduce is supposed to be given a pure function that only relies on its parameters and doesn't mutate any values. You're trying to produce an array, which would either involve creating the array and then mutating it (adding values), or creating copies of the array (via concat), like this:
const results = incomes.reduce((agg, v) =>
v.date
? agg.concat([v])
: agg.slice(0, -1)
.concat([{
...agg.slice(-1)[0],
description: `${agg.slice(-1)[0].description}, ${v.description}`}]),
[])
As you can see, there's a lot of duplicative sliceing and concating going on here, which is wasteful from a performance perspective. Perhaps more importantly, it's hard to reason with and hard to debug. I'd probably stick with using a for loop that tracks state and pushes to an array instead.
let results = [];
for (let v of incomes) {
if (v.date) {
results.push({...v});
} else {
results[results.length - 1].description += ", " + v.description;
}
}
Currently I am trying to create a JSON object in java script which has an additional array containing all of the data that I currently posses:
src is a JSON object which before any code is run is equal to:
[
{
_id: new ObjectId("629ac43586b27bfd70337d06"),
Title: 'Test Poll',
Option: [ 'Test Option 1', 'Test Option 2', 'Test Option 3' ]
},
{
_id: new ObjectId("629afc9286b27bfd70337d09"),
Title: 'Test Poll 2',
Option: [ 'Test Option 1' ]
}
]
I need to reformat this object so that it is contained within a separate array which I am currently attempting to do with this line:
var context = { poll:src };
This results in a reformatting of the JSON object which I do not understand, after running this code context contains:
poll: [
{
_id: new ObjectId("629ac43586b27bfd70337d06"),
Title: 'Test Poll',
Option: [Array]
},
{
_id: new ObjectId("629afc9286b27bfd70337d09"),
Title: 'Test Poll 2',
Option: [Array]
}
]
It gets rid of the Option arrays and replaces them with [Array]. I need to keep these arrays and I am not sure what to change to fix this as I have tried looking elsewhere for answers. Does anyone have an idea of what is going on here?
Ok they are arrays I am just too new to realize that it would not print fully. I was attempting to use handlebars on these Option arrays to print the list and I was forgetting to use the implicit this for the variable name instead of just 'Option'.
Problem solved.
i have an array of objects that is coming from server.
data:[
{
// values
}
]
below is one object element of that array.
0:
assignedTo:{
name: "Shokat iqbal"
},
category:{
name: "Fan"
},
complainer:{
name: "Testt"
},
details: "Makk Amjum and my name is yeh and i amthose who is ur father"
location: "Room number 87 blockasdas jknaksdnkaj knasdkan kasndka nasdkas"
status: "in-progress"
title: "My fan is damaged"
_id: "5cade948e0b7ce30c8ef2f05"
i want to extract some of its properties like
Assignee: assignedTo.name, category: Category.name, Complainer:complainer.name
and want to make another array of objects which will look like this.
[
{
Assignee: assignedTo.name,
Complainer: complainer.name,
Category: category.name,
title: title,
location: location,
details: details
}
]
please help me how to do this?
Welcome to SO. It's always good to try and show, or talk about some of the solutions that you have tried and where they failed. The community is great but they also appreciate people trying.
Array.map will do the trick for you
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const formattedData = data.map(record => ({
Assignee: record.assignedTo.name,
Complainer: record.complainer.name,
Category: record.category.name,
title: record.title,
location: record.location,
details: record.details,
}));
I'm trying to get the key of these json objects in order to create a new object with extra filed to create table headers in a React app. JSON data:
let example = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Paris',
},
]
The function:
getKeys() {
return example.map((key) => {
return {
cityName: key, // gets the whole array
capital: false,
};
});
}
I tries Object.keys( example);, it returns integers; 0, 1.
How can I get the keys in this case? Thanks.
You are trying to map the keys for an array since example is an array. If the data are consistent throughout the array get the first element example[0] and do Object.keys().
So Object.keys(example[0])
There's no need to get the keys if you just want to add a property to the items in the array. I think there's a misunderstanding about .map, which gives you a single item/object in the array, not the keys.
Something like this perhaps?
let example = [{
id: 1,
city: 'New York',
}, {
id: 2,
city: 'Paris',
}];
const modifiedArray = function(arr) {
return arr.map(item => {
return {
id: item.id,
cityName: item.city,
capital: false,
};
})
}
const newArray = modifiedArray (example);
console.log(newArray )
I have a web app which uses MongoDB as database and I'm trying to iterate thru multiple values inside a single property named passport.
This is my schema:
var EmployeeDBSchema = new Schema({
/* Passport tab schema */
passportInfo: {
passportDetails: []
},
And here's how it looks in Robomongo:
I tried checking if this can be retrieved as an array, so I did below:
console.log(_.map(results, _.property('passportInfo')));
passportArr = _.map(results, _.property('passportInfo'));
console.log("is passport array? " + _.isArray(passportArr));
Result:
Now since it was positive, I tried iterating thru it like a normal array using the ff. code:
_.forEach(passportArr, function (value, key) {
_.forEach(passportArr[key], function(value2, key2){
console.log(key2 + " >> " + value2);
});
});
However, what I got was this:
How can I get the values of passportExpiry, passportNumber and countryOfOrigin?
I'm really having a hard time over this. Hoping somebody can help.
Thank you.
EDIT: Not sure if this will help but, I got the idea for the structure from this Plunker. Main idea behind Passport was the user can add an unlimited number of passport information (hence the passportInfo array). I'm trying to retrieve the data here so I can render it as a CSV file.
UPDATE:
Here's the expanded results as requested (from console.log):
full results
[ { _id: dummyiddontmind123,
employeeID: '123asd12',
desiredRoleOther: 'Other role',
desiredRole3: 'Role 3',
desiredRole2: 'Role 2',
desiredRole1: 'The Role',
isOpenToIntlAssignment: 'Y',
employeeName: 'Jane Doe',
yrsInIT: 1,
visaInfo:
[ { visaCountryOfOrigin: [Object],
visaNumber: 'asd',
visaEntry: 'Single',
visaExpiry: '2017-03-16T16:00:00.000Z',
visaStatus: 'expired' } ],
passportInfo:
[ { countryOfOrigin: [Object],
passportNumber: [Object],
passportExpiry: '2017-03-03' },
{ countryOfOrigin: [Object],
passportNumber: [Object],
passportExpiry: '2017-03-08T16:00:00.000Z' },
{ countryOfOrigin: [Object],
passportNumber: [Object],
passportExpiry: '2017-03-10T16:00:00.000Z' } ] } ]
[ [ { passportExpiry: '2017-03-03',
passportNumber: { '0': 'EB1234567' },
countryOfOrigin: { '0': 'Philippines' } },
{ passportExpiry: '2017-03-08T16:00:00.000Z',
passportNumber: { '1': 'AS1234' },
countryOfOrigin: { '1': 'Japan' } },
{ passportExpiry: '2017-03-10T16:00:00.000Z',
passportNumber: { '2': 'AX123' },
countryOfOrigin: { '2': 'Singapore' } } ] ]
Your data inside passportInfo is a bit off, probably due to some copy-paste error after outputting it.
I take it you want to export all stored passport information into a csv of format country; number; expiry.
The first thing you want to make sure is that the actual data and the data you expect are structurally the same. If not, you can still add transformation steps before (e.g. flatten arrays or transform objects from {0: 123} to [123]).
As soon as this is under control, you can start by mapping the objects of employee.passportInfo from a structured object to an array of information necessary for your csv. This happens using Array.prototype.map.
I added another step inside that map to make sure an object of passportInfo.passportNumber of the form {0: 123} is transformed into an array [123]. This array is then used to map to a single line of your csv by adding passportInfo.countryOfOrigin and .passportExpiry.
// The following code snippets only operates on one employee. If you have an array use an iteration function depending on your needs.
const employee = { _id: 123,
employeeID: '123asd12',
desiredRoleOther: 'Other role',
desiredRole3: 'Role 3',
desiredRole2: 'Role 2',
desiredRole1: 'The Role',
isOpenToIntlAssignment: 'Y',
employeeName: 'Jane Doe',
yrsInIT: 1,
visaInfo: [ {
visaCountryOfOrigin: [Object],
visaNumber: 'asd',
visaEntry: 'Single',
visaExpiry: '2017-03-16T16:00:00.000Z',
visaStatus: 'expired' }
],
passportInfo: [ {
countryOfOrigin: 'ABC',
passportNumber: { 0: '123123123' },
passportExpiry: '2017-03-03'
}, {
countryOfOrigin: 'DEF',
passportNumber: { 0: '321321321', 1: '123123123' },
passportExpiry: '2017-03-08T16:00:00.000Z'
}, {
countryOfOrigin: 'GHI',
passportNumber: { 0: '654654654' },
passportExpiry: '2017-03-10T16:00:00.000Z'
} ]
};
const flattenPassportNumbers = numbers =>
Object.keys(numbers).map(key => numbers[key]);
const info = employee.passportInfo.map(({passportNumber, passportExpiry, countryOfOrigin}) =>
flattenPassportNumbers(passportNumber).map(number =>
[countryOfOrigin, number, passportExpiry]
)
);
const flattenLine = ([line]) => line;
const joinLine = (line) => line.join('; ');
const lines = info.map(flattenLine);
console.log(lines.map(joinLine));
console.log(lines.map(joinLine).join('\n'));
If there's something you don't understand, please don't hesitate to ask.