replace strings with object from other json files - javascript

I have 3 json files:
sources.json
destination_level1.json
destination_level0.json (final file)
I want to "merge" all theses files by replacing matching strings e.g
destination_level0 -> destination_level1 -> sources
in words: "Check the keys in destination_level0 e.g. "Element1", go to destination_level1 and look for a matching object and replace Element1 in destination_level0 with that object." Same goes on from destination_level1 to sources.
Sources might look like this:
{"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}}
destination_level_1 like this:
{"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]}
and destination_level_0 like this:
{"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]}
The final result should look like this:
{"FinalA": [[["A","B"],{"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]},...
I have tried some lodash & underscore, but got stuck.
Any ideas?

Just in pure JavaScript
var sources = {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}};
var destination_level_0 = {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]};
var destination_level_1 = {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]};
var final = {};
for(var key in destination_level_0){
var preFinal = [];
var elems = destination_level_0[key];
for(var i in elems){
var elem = elems[i];
var names = destination_level_1[elem];
for(var j in names){
var name = names[j];
var finalItem = sources[name];
preFinal.push(finalItem);
}
}
final[key] = preFinal;
}
console.log(final);
console.log(JSON.stringify(final));

Map an item from level0 => level1 => level2 using Array#.map inside Array#map (or lodash's _.map()):
var level0 = {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]};
var level1 = {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]};
var level2 = {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}}
;
var result = Object.keys(level0).reduce(function(r, key) {
r[key] = level0[key].map(function(element) {
return level1[element].map(function(item) {
return level2[item];
});
})
return r;
}, Object.create(null));
console.log(JSON.stringify(result));

Related

Javascript Appending to 2-D Array

I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}

Add Dictionaries Keys Values to Array [JavaScript]

Here is a sample of my data structure in JavaScript:
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
How can I add each "username" to a new array (var result = [])?
A sample of the final data structure would be:
var result = ["admin1", "admin2", "admin3", "admin4", "admin5"];
Thank you *
Use Array#map method to generate an array by iterating over the elements.
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
var res = list.map(function(o) {
return o.username
});
console.log(res);
With ES6 arrow function:
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
let res = list.map(o => o.username);
console.log(res);
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
var array=[];
for (var key in list) {
let value = list[key];
console.log(value.username);
array.push(value.username);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

javascript array push issue

I have the below object:
Configs = {};
Configs['category'] = [];
Configs['category']['prod1'] = [];
Configs['category']['prod1'].hosts ={
'table': {
'count': 'total_remaining',
'specs': [
{
'name': 'Test 1',
'code': 'BrandName.Cat.Code.[X].Price'
}
]
}
};
I am trying to create an array of elements to be requested from the database using the code below:
var data = Configs["category"]["prod1"].hosts.table;
var count = [data.count];
var names = data.specs;
var namesArray = names.map(function(names) {
var str = names['code'];
var requiredPortion = str.split("[X]");
var newStr = requiredPortion[0];
return newStr;
});
requestData = namesArray.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]); //remove duplicates
requestData.push(count);
console.log(count);
console.log(requestData);
The desired output is:
["BrandName.Cat.Code.", "total_remaining"]
But, when executing my code I am getting the following output:
["BrandName.Cat.Code.", Array[1]]
I am attaching a fiddle link for this. I guess the issue is with array push function usage. Please help.
You just have to remove the square bracket outside the count variable initialization. Try:
var count = data.count;
Instead of:
var count = [data.count];
Fiddle updated.
Replace var count = [data.count]; with count = Object.keys(data).length
Maybe this helps.

Javascript table string to array

I have a string that looks like:
<tr><td>Date</td><td>Value</td></tr>
<tr><td>2013-01-01</td><td>231.198</td></tr>
<tr><td>2013-02-01</td><td>232.770</td></tr>
<tr><td>2013-03-01</td><td>232.340</td></tr>
<tr><td>2013-04-01</td><td>231.485</td></tr>
<tr><td>2013-05-01</td><td>231.831</td></tr>
<tr><td>2013-06-01</td><td>232.944</td></tr>
<tr><td>2013-07-01</td><td>233.318</td></tr>
...which is of course essentially a table.
I'd like to dynamically convert this string into an array containing 2 arrays. One of dates, one of values.
[Edited in]
An array of objects with date and values would work too.
The following::
var input = // your string
var output = $(input).slice(1).map(function(i,el) {
var tds = $(el).find("td");
return { "date" : tds.eq(0).text(), "value" : tds.eq(1).text() };
}).get();
...will return an array of objects in this format:
[{"date":"2013-01-01","value":"231.198"}, {"date":"2013-02-01","value":"232.770"}, ... ]
If you'd like each value to be treated as a number you can convert it like so:
return { "date" : tds.eq(0).text(), "value" : +tds.eq(1).text() };
// add the unary plus operator ---------------^
Then the result will be:
[{"date":"2013-01-01","value":231.198}, {"date":"2013-02-01","value":232.77}, ... ]
While you've already accepted an answer, I thought I'd post a plain JavaScript solution (albeit largely because I spent time working on it, before Barmar pointed out that you're willing and able to use jQuery):
function cellContents(htmlStr, what) {
var _table = document.createElement('table');
_table.innerHTML = htmlStr;
var rows = _table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText',
cells,
matches = {};
for (var w = 0, wL = what.length; w < wL; w++) {
matches[what[w]] = [];
for (var r = 1, rL = rows.length; r < rL; r++) {
cells = rows[r].getElementsByTagName('td');
matches[what[w]].push(cells[w][text]);
}
}
return matches;
}
var str = "<tr><td>Date</td><td>Value</td></tr><tr><td>2013-01-01</td><td>231.198</td></tr><tr><td>2013-02-01</td><td>232.770</td></tr><tr><td>2013-03-01</td><td>232.340</td></tr><tr><td>2013-04-01</td><td>231.485</td></tr><tr><td>2013-05-01</td><td>231.831</td></tr><tr><td>2013-06-01</td><td>232.944</td></tr><tr><td>2013-07-01</td><td>233.318</td></tr>";
console.log(cellContents(str, ['dates', 'values']));
JS Fiddle demo.
For a pure JavaScript solution you can try something like this (assuming str holds your string) :
var arrStr = str.replace(/<td>/g, "").replace(/<tr>/g, "").split("</td></tr>");
var arrObj = [];
var arrData
for (var i = 1; i < arrStr.length - 1; i++) {
arrData = arrStr[i].split("</td>");
arrObj.push({ Date: arrData[0], Value: arrData[1] })
}
It's a burte-force string replacement/split, but at the end arrObj will have array of objects.
if its a valid html table structure, wrap it between table tags, and use jquery to parse it.
then use jquery's selectors to find the columns.
e.g something like this ( pseudo code, havent tried it )
table = $(yourTableString);
dates = table.find("tr td:nth-child(1)");
values = table.find("tr td:nth-child(2)");
Using jQuery:
var table = $('<table>'+str+'</table>');
var result = {};
table.find('tr:gt(0)').each(function () {
var date = $(this).find("td:nth-child(1)").text();
var value = $(this).find("td:nth-child(2)").text();
result[date] = value;
}
:gt(0) is to skip over the header line. This will create an associative array object that maps dates to values. Assuming the dates are unique, this is likely to be more useful than two arrays or an array of objects.

Is it possible to replace sub object with other object in main object?

I want to replace the sub object with some other object in main object.
ex:
var mianobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var newsubobj = {"n":"8888","g":"9999"}
console.log(mainobj.a.aa)
// this gives the sub object --> {"aaa":"0000","bbb":"1111"}
I want to replace this object with newsubobj.
I need the result as ::
console.log(mainobj);
// {"a":{"aa":{"n":"8888","g":"9999"}},"b":"222","c":"333"}
Thanks in advance.
Why you don't do it like that:
mainobj.a.aa = newsubobj
?
Ah, now we're getting somewhere. To update your question you have:
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var subobjpath = "a.aa"; // this needs to be a string
var newsubobj = {"n":"8888","g":"9999"}
and you want to use subobjpath to replace a part of mainobj with newsubobj.
You can do so using code like this:
var path = subobjpath.split('.');
var obj = mainobj;
for(var idx=0; idx < path.length-1;idx++) obj = mainobj[path[idx]];
obj[path[path.length-1]] = newsubobj;
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"};
var newsubobj = {"n":"8888","g":"9999"};
mainobj.a.aa = newsubobj;
console.log(mainobj);

Categories

Resources