I have some raw imdb data in two strings:
var headers = "ID imdbID Title Year Rating Runtime Genre Released Director Writer Cast Metacritic imdbRating imdbVotes Poster Plot FullPlot Language Country Awards lastUpdated";
const content = "1 tt0000001 Carmencita 1894 NOT RATED 1 min Documentary, Short William K.L. Dickson Carmencita 5.8 1136 http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng##._V1_SX300.jpg Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face. USA 2016-05-04 00:03:31.600000000";
Of course I am cleaning out the tabs and spaces etc and creating two arrays like so:
const values = content.split(/(\t+)/).filter( (part) => !/\t/.test(part) );
let keys = headers.split(/(\s+)/).filter( (part) => !/\s+/.test(part) );
Now I want to map the keys in keys array to the values in the values array accurately. So I do a reduce like so:
var result = {};
values.reduce( (acc, val, index) => {
return result[ keys[index] ] = val;
}, result);
This gives me back a final result object that looks like this:
{
Cast: "1136",
Director: "Carmencita",
Genre: "Documentary, Short",
ID: "1",
imdbID: "tt0000001",
imdbRating: "Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face.",
imdbVotes: "USA",
Metacritic: "http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng##._V1_SX300.jpg",
Poster: "2016-05-04 00:03:31.600000000",
Rating: "NOT RATED",
Released: "William K.L. Dickson",
Runtime: "1 min",
Title: "Carmencita",
Writer: "5.8",
Year: "1894"
}
As you can see, the order is all mixed up! How do I get the right order in my data so I get title key mapped to the movie title value etc. ?
I am open to using a library like lodash to achieve this but can't tell what I should use? Here is a jsbin demo of the present state: https://jsbin.com/gekawi/edit?js,console
If you take the raw data with the tabs inside, you could use them for splitting.
var headers = "ID imdbID Title Year Rating Runtime Genre Released Director Writer Cast Metacritic imdbRating imdbVotes Poster Plot FullPlot Language Country Awards lastUpdated",
content = "1 tt0000001 Carmencita 1894 NOT RATED 1 min Documentary, Short William K.L. Dickson Carmencita 5.8 1136 http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng##._V1_SX300.jpg Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face. USA 2016-05-04 00:03:31.600000000",
headerArray = headers.split(/\t/),
contentArray = content.split(/\t/),
object = {};
headerArray.forEach(function (k, i) {
object[k] = contentArray[i];
});
console.log(object);
Related
I have a json like
{
"connectEnd": 1366.2749999930384,
"connectStart": 175.91999999422114,
"decodedBodySize": 3360,
"domComplete": 10424.984999990556,
"domContentLoadedEventEnd": 6581.454999992275,
"domContentLoadedEventStart": 6581.454999992275,
"domInteractive": 6581.420000002254,
"domainLookupEnd": 175.91999999422114,
"domainLookupStart": 12.000000002444722,
"duration": 10425.015000000712,
"encodedBodySize": 1279,
"entryType": "navigation",
"fetchStart": 0.22499999613501132,
"initiatorType": "navigation",
"loadEventEnd": 10425.015000000712,
"loadEventStart": 10424.994999993942,
"name": "https://something/login",
"nextHopProtocol": "http/1.1",
"redirectCount": 0,
"redirectEnd": 0,
"redirectStart": 0,
"requestStart": 1366.394999990007,
"responseEnd": 2062.7999999996973,
"responseStart": 2059.7599999891827,
"secureConnectionStart": 414.94000000238884,
"serverTiming": [],
"startTime": 0,
"transferSize": 2679,
"type": "navigate",
"unloadEventEnd": 0,
"unloadEventStart": 0,
"workerStart": 0,
"workerTiming": []
}
I used papaparse to convert JSON into csv and I am getting this:
"Request time","Time to first byte","Response time","Request Response time","Cache seek plus response time","Dom interactive","Dom complete","Transfer Size","duration","Domain lookup time taken","Connection time taken"
693.3649999991758,3.040000010514632,3.040000010514632,696.4050000096904,2062.5750000035623,6581.420000002254,10424.984999990556,2679,10425.015000000712,163.91999999177642,1190.3549999988172
I am planning to use Jenkins plugin called BenchMark Evaluator
This plugin accepts csv only in this format:
csv table image link
My problem statement: How I change the structure of parsed csv into the desired csv format. Is there a npm package that can give me directly what I want or the parsed csv needs to be converted.
A more elegant way to convert json to csv is to use the map function without any framework:
var json = json3.items
var fields = Object.keys(json[0])
var replacer = function(key, value) { return value === null ? '' : value }
var csv = json.map(function(row){
return fields.map(function(fieldName){
return JSON.stringify(row[fieldName], replacer)
}).join(',')
})
csv.unshift(fields.join(',')) // add header column
csv = csv.join('\r\n');
console.log(csv)
Output:
title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
"Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
"Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"
Use this less dense syntax and also JSON.stringify to add quotes to strings while keeping numbers unquoted:
const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
header.join(','), // header row first
...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')
console.log(csv)
Example Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company ew So here is example of the string, I want to split it like that it consider Company 1 as one company and company, Inc. as one, but here got situation in company, Inc. it condidering 2 companies while this logic. how can I resolve this? Lke with such strings company, Inc. I want to consider it one element only
const company = company.split(",");
Here the string can be anything, this is just example for the string, but it can be any name. So I am looking for generic logic which works for any string, having same structure of string.
Note $ ==(,) represents as separation point, kept to get clarity that from that point I need to separate the string
Object:
Example 1
{
_id: 5de4debcccea611e4d14d4d5
companies: One Bros. Inc. & Might Bros. Dist. Corp.$Pages, Inc.$Google Inc. Search$Aphabet Inc. tech.
}
Example 2
{
_id: 5de4debccc333611e4d14d4f5
companies: Google Comp. Inc.$Google Comp. Inc. Estd.$Tree, Ltd.$Tree, Ltd.
}
First I split on 'ompany' rather than 'company', because you have one instance of 'Company' with a capital C -- see the output of the first console log within a comment below.
Then I put things back together using reduce -- map is not the right choice here, as I need an array that is one fewer than the size of the fragments I generated. Then though since I need an array that corresponds to the number of strings we want to return, which is one fewer than the number of fragments, the first thing I do inside my reduce is ensure I do not look beyond the end of the array.
Then I split each fragment and pop off the last element, which just puts either "C" or "c" back together with "ompany". Then I replace any trailing ',c' from the next fragment with an empty string, and add the result to the company. Finally I add the entire result to the array I'm generating with reduce. See comment results at bottom. Also here it is on repl.it: https://repl.it/#dexygen/splitOnCompanyStringLiteral
This is a fairly concise way to do this but again if you can do anything to improve your data, you won't have to use such unnecessarily complicated code.
const companiesStr = "Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company ew";
const companySuffixFragments = companiesStr.split("ompany");
console.log(companySuffixFragments);
/*
[ 'C', ' 1,c', ' ltd 2,c', ', Inc.,c', ' Nine nine, ltd,c', ' ew' ]
*/
const companiesArr = companySuffixFragments.reduce((companies, fragment, index, origArr) => {
if (index < companySuffixFragments.length - 1) {
let company = fragment.split(',').pop() + 'ompany'
company = company + origArr[index + 1].replace(/,c$/, '');
companies.push(company);
}
return companies
}, []);
console.log(companiesArr);
/*
[ 'Company 1',
'company ltd 2',
'company, Inc.',
'company Nine nine, ltd',
'company ew' ]
*/
First change , with any other symbol. I am using & here and then split string with ,
var str= 'Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company ew';
str = str.replace(', Inc.','& Inc.');
/*str = str.replace(', ltd','& ltd');*/
console.log(str.split(',').map((e)=>{return e.replace('&',',').trim()}));
try with the below solution.
var str = ["company 1","company ltd 2","company", "Inc.","company Nine nine", "ltd","company ews"];
var str2 =str.toString()
var str3 = str2.split("company")
function myFunction(item, index,arr){if(item !=""){let var2 = item.replace(/,/g," ");var2 = "Company"+var2;arr[index]=var2;} }
str3.forEach(myFunction)
OUtput:
str3
(6) ["", "Company 1 ", "Company ltd 2 ", "Company Inc. ", "Company Nine nine ltd ", "Company ews"]
And remove the first element of the array.
As has been commented I'd try to get a more clean String so that you don't have to write "strange" code to get what you need.
If you can't do that right now this code should solve your problem:
let string = 'Company 1,company ltd 2,company, Inc.,company Nine nine, ltd,company
ew';
let array = string.split(',');
const filterFnc = (array) => {
let newArr = [],
i = 0;
for(i = 0; i < array.length; i++) {
if(array[i].toLowerCase().indexOf('company') !== -1) {
newArr.push(array[i]);
} else {
newArr.splice(newArr.length - 1, 1, `${array[i - 1]}, ${array[i]}`);
}
}
return newArr;
};
let filteredArray = filterFnc(array);
How can i remove all instances of :smile: style emjois from a string using javascript? Here is an example below I got in JSON with :point_right: in it. I'd love to remove all of them from a string.
[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }
Just use String.prototype.replace() with a regular expression:
const input = 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”';
const output = input.replace(/:\w+:/g, '');
console.log(output);
Assuming the emojis are all one word, between :s:
const obj = {
service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299'
}
obj.title = obj.title.replace(/:[^ ]+:/g, '');
obj.text = obj.text.replace(/:[^ ]+:/g, '');
console.log(obj);
From this answer Replacing values in JSON object you could do this :
var json=[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }];
var rep = JSON.stringify(json).replace(/(“)(:[^:]+:)/g, '$1');
var New = JSON.parse(rep);
console.log(New);
Try this :
// JSON Object
var jsonObj = [{
"service_name": "Instagram",
"title": "Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”",
"text": "36 Likes, 2 Comments - “:point_right: Real people, making real products",
"ts": "1523497358.000299"
}];
// Replace :point_right: with blank string.
jsonObj.map(obj => {
obj.title = obj.title.replace(":point_right: ", "");
obj.text = obj.text.replace(":point_right: ", "");
return obj;
});
// Output
console.log(jsonObj);
I have to create an object, three instances of objects and arrays.
Create a cruise object that has the following properties:
Cruise Date,
Cruise Destination,
Cruise Description,
Cruise URL,
Ship Name,
Ship Description,
Ship URL,
Price
Make three instances of the cruise object.
Create an array of the three instances.
According to my understanding I created one cruise object with all properties mentioned and I have to create three more instances of object.
I did the following. Does creating instances means creating object of same type?
function Cruise(cruise_Date, cruise_Destination, cruise_URL, ship_Name, ship_Description, ship_url, price ) {
this.cruise_Date = cruise_Date;
this.cruise_Destination = cruise_Destination;
this.cruise_URL = cruise_URL;
this.ship_Name = ship_Name;
this.ship_Description = ship_Description;
this.ship_url = ship_url;
this.price = price
}
var myCruise = new cruise("16 March 2018",
'4 Night Bahmas cruise ',
"You know the name, the laid-back attitude and where to find them, but you’ll just have to visit The Bahamas to truly appreciate this classic cruise destination. On this 700-strong string of sun-splashed islands dotting the blue Atlantic, the living’s easy. (And it’s not bad on a Bahamas cruise either!) The central port of Nassau is the bustling capital of the country — bustling is a relative term, of course — while Freeport is all chill, all the time. And nothing is as delightfully desolate as Half Moon Cay and Princess Cays: pure private-destination paradise",
"https://www.ncl.com/cruise-destinations/bahamas-florida-cruises?cid=PS_TSI_CAL_DST_GOO-g_LEN_SRH_DESTBAF_3%20night%20bahamas%20cruise_NA_189086496943&kshid=998d4956-0345-4c42-88fb-0f1ce25bfbf9&kwid=659072&anchor=NA&gclid=Cj0KEQjw3rfOBRDJruDR8Ljm7e0BEiQAam-GsPAAXfpiBInuQfwSq6ZOe4U2KBmlRbc08kFl-gFJIBQaAtvn8P8HAQ",
'Majesty of the sea ', "MS Majesty of the Seas is a Sovereign-class cruise ship owned by Royal Caribbean Cruises Ltd and operated by Royal Caribbean International. ", "https://www.royalcaribbean.com/cruise-ships/majesty-of-the-seas",
'$' + 169);
var myCruise2 = new cruise("Cruise_Date", "Cruise_Destination", "Cruise_Description", "Cruise_URL", "Ship_Name", "Ship_Description", "Ship_URL", "Price");
var myCruise3 = new cruise("Cruise_Date", "Cruise_Destination", "Cruise_Description", "Cruise_URL", "Ship_Name", "Ship_Description", "Ship_URL", "Price");
list = new Array("Departs", "Destination", "Ship", "Price from");
instances = new Array(myCruise, myCruise2, myCruise3);
function displayList(the_date, ) {
// body...
}
expected output:
Your code in creating objects has a few problems. You would need to have an object constructor function named cruise() for that to work. Usually you capitalize object constructor functions. Also, I doubt they intended for you to give values of each property that are the same as the names of the properties. If you are giving an instance of an object of a cruise, you would give it an actual destination like "The Bahamas", etc. An object constructor function would look something like this:
function Cruise(date,destination,descr,url,name,price){
this.cruiseDate = date;
this.cruiseDestination = destination;
this.cruiseDescription = descr;
this.cruiseUrl = url;
this.cruiseName = name;
this.cruisePrice = price;
}
As for creating an array of objects, after you make the instances of the objects with actual values in them similar to how you did them, you could just put them in an array literal, unless you were supposed to do it another way.
var instances = [myCruise,myCruise2,myCruise3];
I was just wondering how I could search and compare two string object and check if either contains a matching string.
I have an associative array containing terms and explanations.
I also have this array broken into two objects "keys"(keys showing the key of the associative array) and "values"(values showing the value of each key in array).
I have another associative array containing a dish and its explanation.
I have split the dish's description into separate words put them into an object.
What I would like to do now is check for every word in descsplit search the TermList and return explanation of term found if found.
eg. free-range is contained in dish explanation, check if there is a match for free-range in TermList and return the value(explanation) of free-range.
Any help would be greatly appreciated, Thanks.
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var values = []; // Creating an object for the values of the terms in TermList
var keys = []; // Creating an object for the keys of the terms in TermList
//function to assign the keys of terms to object keys.
function showkey() {
for (var key in TermList) {
if (TermList.hasOwnProperty(key)) {
keys.push(key);
}
}
//function that shows the value of each key in TermList.
function showValue(){
for( var value in TermList){
values.push(TermList[value]);
}
showkey();
showValue();
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var descsplit = [];
function SplitDesc() {
for (var value in DishList) {
descsplit.push(DishList[value].split(/[\s.,?!:]+/)); // Splits the values of the key up in Dishlist, and puts them into array.Also makes them avoid punctuations while splitting.
}
}
SplitDesc();
//For every word in descsplit search the TermList and return explanation of term found if found
Not tested fully, but this may work
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var keys = Object.keys(TermList);
for(var key in DishList){
var val = DishList[key];
for(var iIndex=0;iIndex<keys.length ;iIndex++){
var term = keys[iIndex];
var regx = new RegExp('\\b'+term+'\\b',"gi");
var found = null;
while((found = regx.exec(val))!=null){
console.log('Found term "'+ term+ '" at index '+found.index);
}
}
}