-2

I have this code with several objects.

function Nums( use, dep, unt, prt, no){
  this.uses = use;
  this.department = dep;
  this.units = unt;
  this.part = prt;
  this.numbers = no;
}

  var n1 = new Nums( "use1", "depart1", "unit1", "part1", "3562")
  var n2 = new Nums( "use2", "depart2", "unit2", "part2", "5226" )

and I want to search a keyword in objects for example " 5 " .

 var obj = [n1, n2],
     res = [],
     srch = "5"
for( i = 0; i<obj.length; i++){
    for( key in obj[i]){
      if(obj[i][key].includes(srch)){
        res.push(obj[i])
         }
       }
     }

but I want to save every object in a new variable. and then print variables in a html tag.

for( itm in res[0]){
       r1 +=  res[0][itm] ;
     }
     for( itm in res[1]){
       r2 +=  res[1][itm] ;
     }.........


<p> r1 <p> <p> r2 <p> .....

how to write it?

see code

Ahmad MRF
  • 1,346
  • 1
  • 6
  • 16
  • please add some data, what you have and what you like to get. – Nina Scholz Dec 12 '18 at 10:15
  • Something like this ? https://stackoverflow.com/questions/53727548/using-a-variable-increment-to-create-new-variables-in-javascript/53727902#53727902 I answered recently on a "similar" question. – Takit Isy Dec 12 '18 at 10:15
  • That smells like an x/y problem. https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem I cannot imagine a meaningful usecase for such an approach. – connexo Dec 12 '18 at 10:17
  • @connexo I think the questioner is just trying to express what he requires, not necessarily as a solution. – lloydaf Dec 12 '18 at 10:20
  • Hello ahmad and welcome to SO. Your code looks like it could be done with [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) but I am not sure why every key in the object needs to match the search. Should it not be item.numbers.includes(srch)? – HMR Dec 12 '18 at 10:22
  • Could you please update the question with a sample of the output should look like for a certain `srch` values? – HMR Dec 12 '18 at 10:39

1 Answers1

0

i found my answer in this post : JavaScript: Dynamically Creating Variables for Loops

i need to create new variables for each iteration . and my code become ...:

for( x = 0; x < res.length; x++){
         var results = [];
         for( itm in res[x]){           
           if(result[x] == undefined){
             result[x] = "";
           }
           result[x] +=  res[x][itm] ; 

         }
         out += "<p>" + result[x] + "</p>";
       }


document.innerHTML = out ;
Ahmad MRF
  • 1,346
  • 1
  • 6
  • 16