I have the list of URL like below. How to convert it into complete json object?
My array of URLs.
[
"path1/subpath1/file1.doc","path1/subpath1/file2.doc","path1/subpath2/file1.doc","path1/subpath2/file2.doc","path2/subpath1/file1.doc","path2/subpath1/file2.doc","path2/subpath2/file1.doc","path2/subpath2/file2.doc","path2/subpath2/additionalpath1/file1.doc"
]
I want this as json object like:
{
"path1":{
"subpath1":["file1.doc","file2.doc"],
"subpath2":["file1.doc","file2.doc"]
},
"path2":{
"subpath1":["file1.doc","file2.doc"],
"subpath2":["file1.doc","file2.doc"],
"additionalpath1":{
"additionalpath1":["file1.doc"]
}
}
}
How to do this?
I tried it with the below code snippets. But there are few folder objects are missing.
If you try this code you will find that test1 and additional objects are missing:
<html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p id="demo"></p>
<script>
let paths = [ "admin/640954.jpg", "admin/test1/3m-nd.jpg",
"admin/test1/Acct.png", "admin/test1/additional/111.gif", "admin/test1/additional/Aard.jpg",
"dp/151292.jpg", "dp/151269.jpg", "dp/1515991.jpg" ];
function getMap(urls){
var map = {};
urls.forEach(function(url){
var parts = url.split("/");
makePath(map, parts);
})
return map;
}
function makePath(map,parts){
var currentPath = map;
for(var i = 0 ; i < parts.length - 1 ; i++ ){
if(i == parts.length -2 ){
currentPath[parts[i]] = currentPath[parts[i]] || [];
currentPath[parts[i]].push(parts[++i]);
}else{
currentPath[parts[i]] = currentPath[parts[i]] || {};
currentPath = currentPath[parts[i]];
}
}
}
document.getElementById("demo").innerHTML=JSON.stringify(getMap(paths));
</script>
</body>
</html>
You could use .split("/") and iterate over the results, creating properties in nested objects:
let paths = [
"path1/subpath1/file111.doc",
"path1/subpath1/file112.doc",
"path1/subpath2/file121.doc",
"path1/subpath2/file122.doc",
"path2/subpath1/file211.doc",
"path2/subpath1/file212.doc",
"path2/subpath2/file221.doc",
"path2/subpath2/file222.doc",
"path2/additionalpath3/additionalpath1/file2311.doc"
];
let treePath = {};
paths.forEach(path => {
let levels = path.split("/");
let file = levels.pop();
let prevLevel = treePath;
let prevProp = levels.shift();
levels.forEach(prop => {
prevLevel[prevProp] = prevLevel[prevProp] || {};
prevLevel = prevLevel[prevProp];
prevProp = prop;
});
prevLevel[prevProp] = (prevLevel[prevProp] || []).concat([file]);
});
console.log(treePath);
Or:
let paths = [
"path1/subpath1/file111.doc",
"path1/subpath1/file112.doc",
"path1/subpath2/file121.doc",
"path1/subpath2/file122.doc",
"path2/subpath1/file211.doc",
"path2/subpath1/file212.doc",
"path2/subpath2/file221.doc",
"path2/subpath2/file222.doc",
"path2/additionalpath3/additionalpath1/file2311.doc"
];
let treePath = {};
paths.forEach(path => {
let levels = path.split("/");
let file = levels.pop();
levels.reduce((prev, lvl, i) => {
return prev[lvl] = (levels.length - i - 1) ? prev[lvl] || {} : (prev[lvl] || []).concat([file]);
}, treePath);
});
console.log(treePath);
I have made Half code for you. check if it is helpful for you.
You can use it and can made some changes to achieve your goal.
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = '"path1/subpath1/file1.doc","path1/subpath1/file2.doc","path1/subpath2/file1.doc","path1/subpath2/file2.doc","path2/subpath1/file1.doc","path2/subpath1/file2.doc","path2/subpath2/file1.doc","path2/subpath2/file2.doc","path2/subpath2/additionalpath1/file1.doc"';
var res = str.split(",");
document.getElementById("demo").innerHTML = res[0];
var finalresult = [];
var innerarray = [];
var outer = [];
var outer1 = [];
var inner =[];
jQuery.each( res, function( i, val ) {
res1 = val.split("/");
jQuery.each( res1, function( i2, val1 )
{
if(i2 == 0 && !(outer.includes(val1)))
{
outer.push(val1);
}
else if(i2 == 1 && !(outer1.includes(val1)))
{
outer1.push(val1);
}
else if(!(inner.includes(val1)))
{
inner.push(val1);
}
console.log(outer);
});
});
}
</script>
</body>
</html>
function filePathOject (arr) {
const ret = {};
arr.forEach((path) => {
const dirs = path.split('/');
const filename = dirs.pop();
let dirObject = ret;
dirs.forEach((dir, i) => {
if (i === dirs.length - 1) {
dirObject[dir] = dirObject[dir] || [];
dirObject[dir].push(filename);
} else {
dirObject[dir] = dirObject[dir] || {};
}
dirObject = dirObject[dir];
});
});
return ret;
}
You can do something like this.
var urls = [
"path1/subpath1/file1.doc","path1/subpath1/file2.doc","path1/subpath2/file1.doc","path1/subpath2/file2.doc","path2/subpath1/file1.doc","path2/subpath1/file2.doc","path2/subpath2/file1.doc","path2/subpath2/file2.doc","path2/subpath2/additionalpath1/file1.doc"
]
function getMap(urls){
var map = {};
urls.forEach(function(url){
var parts = url.split("/");
makePath(map, parts);
})
return map;
}
function makePath(map,parts){
var currentPath = map;
for(var i = 0 ; i < parts.length - 1 ; i++ ){
if(i == parts.length -2 ){
currentPath[parts[i]] = currentPath[parts[i]] || [];
currentPath[parts[i]].push(parts[++i]);
}else{
currentPath[parts[i]] = currentPath[parts[i]] || {};
currentPath = currentPath[parts[i]];
}
}
}
getMap()
Left one part for you :)
Maybe you'd prefer to have subdirs in arrays too
const path = '/home/user/dir/file';
var next;
path.split('/').reverse().forEach(name => {
if (name === "") return;
if (typeof(next) === 'undefined') {
next = [String(name)];
} else {
var current = {};
current[name] = next;
next = [current];
}
});
console.log(JSON.stringify(next));
// [{"home":[{"user":[{"dir":["file"]}]}]}]
Then objects can be joined
Related
var allUsers = [{id:1},{id:2},{id:3},{id:4},{id:5}]
var selectedUsers = [{id:1},{id:4}]
How would I return this?
var remainingUsers = [{id:1},{id:2},{id:3},{id:4}]
Hope this will work for you
var allUsers = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]
var selectedUsers = [{ id: 4 }, { id: 1 }]
function compare(a, b) {
let comparison = 0;
if (a.id > b.id) {
comparison = 1;
} else if (a.id < b.id) {
comparison = -1;
}
return comparison;
}
selectedUsers = selectedUsers.sort(compare)
var remainingUsers = allUsers.slice(allUsers.findIndex(x => x.id == selectedUsers[0]['id']), allUsers.findIndex(x => x.id == selectedUsers[1]['id']) + 1)
console.log(remainingUsers);
You could use this approach
var allUsers = [{id:1},{id:2},{id:3},{id:4},{id:5}]
var selectedUsers = [{id:1},{id:4}]
function getRemaining(allUsers, selectedUsers){
var rem = [];
var start = false;
var stop = false;
allUsers.map((x)=>{
if(x.id == selectedUsers[0].id){ start = true; rem.push(x) }
if(x.id == selectedUsers[1].id){ stop = true; rem.push(x) }
if(start && !stop){
rem.push(x)
}
})
return rem
}
getRemaining(allUsers, selectedUsers)
I tried to make an example on your given values. please have a look.
var alluser = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var selected = [{id:1},{id:4}];
var left_users = new Array();
function check_matchuser(ref_id){
var count = 0;
$(selected).each(function(key, value){
if(value.id==ref_id){
count++;
}
});
if(count>0){
return false;
}else{
return true;
}
}//end of check
$(alluser).each(function(key, usersvalue){
var check_status = check_matchuser(usersvalue.id);
if(check_status){
var temp_data = {'id' : usersvalue.id};
left_users.push(temp_data);
}
});
console.log(left_users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var remainingUsers = allUsers.slice(allUsers.findIndex(x=>x.id == selectedUsers[0].id),allUsers.findIndex(x=>x.id == selectedUsers[1].id)+1)
You can use slice.
var allUsers = [{id:1},{id:2},{id:3},{id:4},{id:5}]
var selectedUsers = [{id:1},{id:4}]
var remainingUsers = allUsers.slice(allUsers.findIndex(x=>x.id == selectedUsers[0].id),allUsers.findIndex(x=>x.id == selectedUsers[1].id)+1)
console.log(remainingUsers);
I'm sorry my English is not very good,Maybe you can gets the start and end subscripts and then USES the splice() method.
var allUsers = [{id:1},{id:2},{id:3},{id:4},{id:5}]
var selectedUsers = [{id:1},{id:4}]
function getBetweens(allUsers,selectedUsers){
var start = allUsers.findIndex((item)=>{
return JSON.stringify(item)==JSON.stringify(selectedUsers[0])
})
var end = allUsers.findIndex((item)=>{
return JSON.stringify(item)==JSON.stringify(selectedUsers[1])
})
betweenArray = allUsers.splice(start,end+1)
return betweenArray
}
console.log(getBetweens(allUsers,selectedUsers),'gets')
I've done some searching around the web and nothing seems to solve my problem. I have the following jQuery code:
function youtube_data_parser(data) {
//---> parse video data - start
var qsToJson = function(qs) {
var res = {};
var pars = qs.split('&');
var kv, k, v;
for (i in pars) {
kv = pars[i].split('=');
k = kv[0];
v = kv[1];
res[k] = decodeURIComponent(v);
}
return res;
}
//---> parse video data - end
var get_video_info = qsToJson(data);
if (get_video_info.status == 'fail') {
return {
status: "error",
code: "invalid_url",
msg: "check your url or video id"
};
} else {
// remapping urls into an array of objects
//--->parse > url_encoded_fmt_stream_map > start
//will get the video urls
var tmp = get_video_info["url_encoded_fmt_stream_map"];
if (tmp) {
tmp = tmp.split(',');
for (i in tmp) {
tmp[i] = qsToJson(tmp[i]);
}
get_video_info["url_encoded_fmt_stream_map"] = tmp;
}
//--->parse > url_encoded_fmt_stream_map > end
//--->parse > player_response > start
var tmp1 = get_video_info["player_response"];
if (tmp1) {
get_video_info["player_response"] = JSON.parse(tmp1);
}
//--->parse > player_response > end
//--->parse > keywords > start
var keywords = get_video_info["keywords"];
if (keywords) {
key_words = keywords.replace(/\+/g, ' ').split(',');
for (i in key_words) {
keywords[i] = qsToJson(key_words[i]);
}
get_video_info["keywords"] = {
all: keywords.replace(/\+/g, ' '),
arr: key_words
};
}
//--->parse > keywords > end
//return data
return {
status: 'success',
raw_data: qsToJson(data),
video_info: get_video_info
};
}
}
function getVideoInfo() {
var get_video_url = $('#ytdlUrl').val();
var get_video_id = getUrlVars(get_video_url)['v'];
var video_arr_final = [];
var ajax_url = "video_info.php?id=" + get_video_id;
$.get(ajax_url, function(d1) {
var data = youtube_data_parser(d1);
var video_data = data.video_info;
var player_info = data.video_info.player_response;
var video_title = player_info.videoDetails.title.replace(/\+/g, ' ');
var fmt_list = video_data.fmt_list.split(',');
var video_thumbnail_url = video_data.thumbnail_url;
var video_arr = video_data.url_encoded_fmt_stream_map;
//create video file array
$.each(video_arr, function(i1, v1) {
var valueToPush = {};
valueToPush.video_url = v1.url;
valueToPush.video_thumbnail_url = video_thumbnail_url;
valueToPush.video_title = video_title;
$.each(fmt_list, function(i2, v2) {
var fmt = v2.split('/');
var fmt_id = fmt[0];
var fmt_quality = fmt[1];
if (fmt_id == v1.itag) {
valueToPush.fmt_id = fmt_id;
valueToPush.fmt_quality = fmt_quality;
}
});
video_arr_final.push(valueToPush);
});
});
return video_arr_final;
}
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function fillInOptions(ytOptions) {
//console.log(ytOptions);
//alert(ytOptions[0]);
var ytFill = ytOptions;
console.log(ytFill);
//ytFill.forEach(function(i,v) {
var ytdlOptions = $('#ytdlOptions');
ytFill.forEach(function(i,v) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
return true;
}
function showYTDLLoader() {
$('#ytdlInput').fadeOut(1000, function() {
$('#ytdlLoader').fadeIn(500);
});
var options = getVideoInfo();
//console.log(options);
if (fillInOptions(options) == true) {
//do rest
}
}
function showYTDLOptions() {
return true;
}
function startDownload() {
showYTDLLoader();
}
function hideYTDLLoader() {
$('#ytdlLoader').fadeOut(500);
}
function animateCSS(element, animationName, callback) {
const node = $(element);
node.addClass(animationName);
function handleAnimationEnd() {
node.removeClass(animationName);
node.animationend = null;
if (typeof callback === 'function') callback();
}
node.animationend = handleAnimationEnd();
}
When my button is clicked, I call showYTDLLoader() which gets an array of objects from the YouTube API that looks like this:
[
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=22&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&ratebypass=yes&dur=917.768&lmt=1572418007364260&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5535432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRgIhAIp-4gyUTLoXFetbY0ha_YnR7DJqsp_MNjjIxqDdfPZJAiEA_WPd21jgX9broBcigf8rcSEVoJb2_NX7t3XZQqytsSM%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "22",
"fmt_quality": "1280x720"
},
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=18&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&gir=yes&clen=44248820&ratebypass=yes&dur=917.768&lmt=1572416976690256&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5531432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRQIhANTZJlBHFWQWCnfK11yvLiPUV26c6NzvqIMKjDwmsByMAiBUSy0ZJMo4GdHSiRU4xBDDLxLtzwKZAqAKCiB-1aViDQ%3D%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "18",
"fmt_quality": "640x360"
}
]
But when I try and loop through each entry with fillInOptions(), my loop is never completed because the length is apparently zero. However, when I dump the array using console.log() it tells me the length is 2, and displays the above. I need to be able to add each option to my dropdown.
Thankyou!
UPDATE: Added full code, sorry!
It looks like your .forEach() is the root of the problem. The parameters of a forEach are currentValue, index like this: array.forEach(function(currentValue, index) {}); but it looks like you're using them in the opposite way
Try rewriting that iteration to this:
ytFill.forEach(function(v, i) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
Notice the difference in the order of v and i in the parameters.
I have an array of objects and want to create another array of objects based on.
I want to check if an object is repeated just want to show the count, otherwise show the object itself with count = 1.
<!-- I have an array-->
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
// I want to create another array based on "arr" like the one below
var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
//Any hint please
This may help you. This answer considers name or some identifier will be unique for each object.
counter = {}
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
var obj = {};
var counter = {}
for (var i = 0, len = arr.length; i < len; i++) {
obj[arr[i]['name']] = arr[i];
counter[arr[i]['name']] = (counter[arr[i]['name']] || 0) + 1
}
newArr = new Array();
for (var key in obj){
newArr.push(extend( obj[key], {count:counter[key]}));
}
function extend(a, b){
for(var key in b)
if(b.hasOwnProperty(key))
a[key] = b[key];
return a;
}
console.log(newArr)
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var countNameMapping = {}, finalArr = [];
var arrLength = arr.length;
for(i=0; i<arrLength; i++){
var tempObj = {name:arr[i], price:arr[i].price, occurance:1};
var productName = arr[i].name;
if(countNameMapping[productName] === undefined){
countNameMapping[productName] = tempObj;
}else{
countNameMapping[productName].occurance += 1;
}
}
for(var k in countNameMapping){
finalArr.push(countNameMapping[k])
}
console.log(finalArr );
You can try this one:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var result = [];
arr.map(function(arrObject) {
if (result.length > 0) {
result.map(function(resultObject) {
if (resultObject.name != arrObject.name) {
arrObject.count = 1;
result.push(arrObject);
} else {
resultObject.count++;
}
})
} else {
arrObject.count = 1;
result.push(arrObject);
}
})
console.log(result);
This will provide the result you are looking for:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var map = arr.reduce((accum, item) => {
var obj = accum.get(item.name) || Object.assign({}, item, {count:0});
obj.count++;
return accum.set(item.name, obj);
}, new Map());
var res = [...map.values()];
More or less...
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
// I want to create another array based on "arr" like the one below
// var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
var count = {};
var test = [];
for (var i = 0, len = arr.length; i < len; i++) {
var id = JSON.stringify(arr[i]);
if (count.hasOwnProperty(id)) {
count[id].count++;
} else {
test.push(arr[i]); // Data contamination. Too lazy to copy object
count[id] = test[test.length - 1]; // Could be better.
count[id].count = 1;
}
}
console.log(test);
This is probably what are you looking for:
How does it work?
First, your array arr will use a forEach loop to find each object and if if new you will add it to the results array. The method isNew() will return true if the object is new.
For each new object founded you will count the number of occurrences using findOccurrences() To reduce the number of "loops" you will slice the array according to the index. So you don't need to search again over the already processed data.
So now you can build an new object, using the name, price and count.
Finally, you can push() the new object to the results array.
var arr =[{name:"coke",price:20},{price:20,name:"coke"},{name:"coke",price:20},{name:"kabab",price:250}];
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
arr.forEach(function(obj) {
if (isNew(obj)) {
var counter = findOccurrences(obj, arr.slice(index, arr.length));
var newObj = {
name: obj.name,
price: obj.price,
count: counter
}
results.push(newObj);
}
index++;
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function isNew(newObj) {
var wasFound = true;
if (typeof results != "undefined" && results != null && results.length > 0) {
results.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
return false;
} else {
wasFound = false;
}
});
return !wasFound;
} else {
return true;
}
}
function findOccurrences(newObj, objects) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
count++;
}
});
}
return count;
}
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original"><p>Original Array</p></div>
<div id="results"><p>Results Array</p></div>
Update:
More optimization.
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var accumulator = {};
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32bit integer
}
var c = (hash & 0x0FFFFFFF)
.toString(16)
.toUpperCase();
return '0000000'.substring(0, 7 - c.length) + c;
};
arr.forEach(function(obj) {
var id = JSON.stringify(obj).hashCode();
console.log(id);
if (accumulator.hasOwnProperty(id)) {
accumulator[id].count++;
} else {
results.push(obj);
accumulator[id] = results[results.length - 1];
accumulator[id].count = 1;
}
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original">
<p>Original Array</p>
</div>
<div id="results">
<p>Results Array</p>
</div>
I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});
Let's say i have this:
<form id='foo'>
<input name='bar[name]' />
<input name='bar[age]' />
</form>
How can i get the values of array inputs within the form foo and put them into an associative array/object like this:
var result = {bar:{name:'blah',age:21}};
P.S. I don't want to use any frameworks for this.
I needed to do this myself and after finding this question I didn't like any of the answers: I don't like regex and the others are limited.
You can get the data variable many ways. I'll be using jQuery's serializeArray method when I implement this.
function parseInputs(data) {
var ret = {};
retloop:
for (var input in data) {
var val = data[input];
var parts = input.split('[');
var last = ret;
for (var i in parts) {
var part = parts[i];
if (part.substr(-1) == ']') {
part = part.substr(0, part.length - 1);
}
if (i == parts.length - 1) {
last[part] = val;
continue retloop;
} else if (!last.hasOwnProperty(part)) {
last[part] = {};
}
last = last[part];
}
}
return ret;
}
var data = {
"nom": "123",
"items[install][item_id_4]": "4",
"items[install][item_id_5]": "16",
"items[options][takeover]": "yes"
};
var out = parseInputs(data);
console.log('\n***Moment of truth:\n');
console.log(out);
You can map the elements to an object like this.
function putIntoAssociativeArray() {
var
form = document.getElementById("foo"),
inputs = form.getElementsByTagName("input"),
input,
result = {};
for (var idx = 0; idx < inputs.length; ++idx) {
input = inputs[idx];
if (input.type == "text") {
result[input.name] = input.value;
}
}
return result;
}
var form = document.getElementById( 'foo' );
var inputs = form.getElementsByTagName( "input" );
var regex = /(.+?)\[(.+?)\]/;
var result = {};
for( var i = 0; i < inputs.length; ++i ) {
var res = regex.exec( inputs[i].name );
if( res !== null ) {
if( typeof result[ res[1] ] == 'undefined' ) result[ res[1] ] = {};
result[ res[1] ][ res[2] ] = inputs[i].value;
}
}
var inputs = document.getElementsByTagName('input');
var field_name, value, matches, result = {};
for (var i = 0; i < inputs.length; i++) {
field_name = inputs[i].name;
value = inputs[i].value;
matches = field_name.match(/(.*?)\[(.*)\]/);
if (!results[matches[0]]) {
results[matches[0]] = {};
}
results[matches[0]][matches[1]] = value;
}
This will get you the elements:
var result = {};
var elements = document.forms.foo.getElementsByTagName("input");
for(var i = 0; i < elements.length; i++)
{
/* do whatever you need to do with each input */
}