Home > Software engineering >  how can i extract a result from array in javaScript?
how can i extract a result from array in javaScript?

Time:05-21

window.onload = function() {
    $.ajax({
        url : "/auctionCount.kh",
        data:{memberNo:memberNo},
        success : function(list){
            for(let i=0;i<list.length;i  ){
                console.log(list[i]);
            }
        }
    });
};

enter image description here

I got it as a hashmap type in sql.

I need to extract divno, prevcount, projectname, projectno, viewdif, viewcount separately here but I don't know how

CodePudding user response:

if you like one liner you can do it like this

let data = [{DIVNO: 4, PREVCOUNT: 5, PROJECTNAME: 'xx', PROJECTNO: 21, VIEWCOUNT: 0, VIEWDIF: 0}, {DIVNO: 5, PREVCOUNT: 6, PROJECTNAME: 'xx2', PROJECTNO: 22, VIEWCOUNT: 1, VIEWDIF: 1}];


const result = data.reduce((res, item) => Object.fromEntries(
  Object.entries(item).map(([k, v]) => [k, [...(res[k] || []), v]])
), {})

console.log(result);

CodePudding user response:

You can do something like:

let data = [{DIVNO: 4, PREVCOUNT: 5, PROJECTNAME: 'xx', PROJECTNO: 21, VIEWCOUNT: 0, VIEWDIF: 0}, {DIVNO: 5, PREVCOUNT: 6, PROJECTNAME: 'xx2', PROJECTNO: 22, VIEWCOUNT: 1, VIEWDIF: 1}];
let result = {DIVNO: [], PREVCOUNT: [], PROJECTNAME: [], PROJECTNO: [], VIEWCOUNT: [], VIEWDIF: []};
data.map(r=> {
        result.DIVNO.push(r.DIVNO);
    result.PREVCOUNT.push(r.PREVCOUNT);    
    result.PROJECTNAME.push(r.PROJECTNAME);
    result.PROJECTNO.push(r.PROJECTNO);
    result.VIEWCOUNT.push(r.VIEWCOUNT);
    result.VIEWDIF.push(r.VIEWDIF);
})
console.info(result);
console.info(result.DIVNO);
console.info(...result.DIVNO);

If some values doesn't come in your ajax response, you would need to validate based in certain condition, but its based on your needs.

CodePudding user response:

If you simply wish to access them, you'd just use the dot operator:

console.log(list[i].DIVNO);
console.log(list[i].VIEWDIF);
// etc..

If you want to access the objects key-value pairs, regardless of what they are:

for (const [key, value] of Object.entries(list[i])) {
    console.log(`${key}: ${value}`);
}
  • Related