Add Dictionaries Keys Values to Array [JavaScript] - 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>

Related

how to loop inside '' in javascript

I want to loop inside single quote I have nested loop in my code errors occurs when I try to loop inside the quote
var jsonObj = #json($data);
var borFld = Object.keys(jsonObj);
var all_fields;
var fields_remove = []
var table_id = #json($table_id);
var rows = [];
var htmls = [];
function getFields(){
var my_fields = [];
for(keys in jsonObj){
var item = jsonObj[keys];
var fields = Object.keys(item)
htmls +=
'<tr>'+
for(list in fields) {
var myfields = fields[list]
all_fields = item[myfields]
}
'</tr>'
}
// $('#tb_time_sheet tbody').html(htmls)
}
I guess you get the data as string of JSON object. You should first parse it so that JS can read it.
const parsedJsonObject = JSON.parse('{"name":"Test"}');
After that you can use it inside for loop. If it is not array of object and key value pair
You can get values by:
Object.values(parsedJsonObject);
You can get keys by:
Object.keys(parsedJsonObject);
Then, iterate over keys and get value by:
parsedJsonObject[key]

How to compare two array objects and remove matched objects from one array object

My Code Scenario is:
var Employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees= [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = [?];
You can store selected employees names in an array and then filter Employees array and check if employee's name is in this array:
var employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var selectedEmployees= ["mohan","ranga"];
var result = employees.filter(emp => selectedEmployees.includes(emp.name));
console.log(result);
To programatically get array of strings instead array of objects, you can use map:
var seletedEmployees= [{name:"mohan"},{name:"ranga"}].map(emp => emp.name);
From the code you have given above i think this might work
$.each(student, function(key, value){
if(matchedvalues.indexOf(value.name) < 0)
{
employeesdataAfterremoveSelected.push(value.name);
}
})
Here is a one liner, decomposed to explain :
// Start by filtering the first array on a condition.
employeesdataAfterremoveSelected = Employees.filter(
// Map the array of selected employees to only return the name
e => seletedEmployees.map(_e => _e.name)
// use the includes function to check if the name is in the array
.includes(e.name)
);
In one line :
employeesdataAfterremoveSelected = Employees.filter(e => seletedEmployees.map(_e => _e.name).includes(e.name));
You can use the filter method, something like below (not tested)
var Employees = [{name:"Ram",htno:1245}, {name:"mohan",htno:1246}]
var SelectedEmployess = [{name:"Ram",htno:1245}]
// filter the items from the invalid list, out of the complete list
var employeesdataAfterremoveSelected = Employees.filter((item.name) => {
return !SelectedEmployess.has(item.name);
})
// get a Set of the distinct, valid items
var validItems = new Set(employeesdataAfterremoveSelected);
You can try this:
var Employees = [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees = [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = Employees.filter(name => {
return (name.name !== seletedEmployees[0].name && name.name !== seletedEmployees[1].name)
})
console.log(employeesdataAfterremoveSelected)
var Employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees= [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = Employees.filter(function(val,index) { console.log(val.name)
return !(seletedEmployees.map(function(e) { return e.name; }).indexOf(val.name));
});

replace strings with object from other json files

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));

How to put data into multi dimensional array in js inside the loop

How can we put data into multi dimensional array or json within a loop.
I know that it's possible to store multi dimensional data at one time, but I want it inside the loop as I have described in the code.
var sub_cat_checked_val = [];
sub_cat_checked.each(function (index) {
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
sub_cat_checked_val['key_one']['key_two']='value';
sub_cat_checked_val[sub_cat_id][index] = index:jQuery(this).val();
});
As it's possible in php like $var_name['key1']['key2']['keyn']='value';
sub_cat_checked_val[sub_cat_id] needs to be defined as an array, so add the lines:
if (!sub_cat_checked_val[sub_cat_id]) {
sub_cat_checked_val[sub_cat_id] = [];
}
to define the value as an array if it does not exist.
Try this snippet:
<script>
var k = {};
k.a = {};
k.a.b = {};
k.a.b.c = {};
k.a.b.c.d = 5;
console.log(k);
</script>
I was able to do it with all of you guys help with some of modifications.
Here is what I did:
sub_cat_checked.each(function (index) {
console.log(index_val);
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
console.log(sub_cat_id);
if (sub_cat_checked_val[sub_cat_id] == undefined) {
sub_cat_checked_val[sub_cat_id] = [];
}
sub_cat_checked_val[sub_cat_id][index] = jQuery(this).val();
});
Thanks a lot to all of you.

Convert Array to objects for Jsondata objects in js

Convert Array-String to Object with Javascript or jQuery
here is my array
data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]
expected output is object
data=[{X:7,Y:12.5},{X:8,Y:15},{X:9,Y:12.5}]
how to do that?
You can try something like this:
var data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
item = item.replace(/{/g, "{\"");
item = item.replace(/}/g, "\"}");
item = item.replace(/:/g, "\":\"");
item = item.replace(/,/g, "\",\"");
return JSON.parse(item);
})
console.log(data)
Try this:
data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.join(',');
data = data.replace(/X/g,'"X"');
data = data.replace(/Y/g,'"Y"');
data = JSON.parse("["+data+"]");
Just convert array to string and do clean up that can be parsed to json.
Simple solution is to replace the X and Y with "X" & "Y". In order to create a string key that can be parse as JSON.
data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]
for(var i in data){
tmp = data[i].replace("X",'"X"').replace('Y','"Y"')
data[i] = JSON.parse(tmp)
}
Enjoy.
var reg = /[^{,]+?(?=:)/g;
var data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
return JSON.parse(item.replace(reg, "\"$&\""));
});

Categories

Resources