1

I have an array in the object that contain class names of an HTML element.now i want a particular class name from an array and want to store in some variable but i don't know full class name.so how can i achieved this.

var arr = ["tile", "tile-2", "tile-new", "tile-position-1-4", value: "tile tile-2 tile-new tile-position-1-4"];

So here i need tile-position-1-4 to be get fetch from array and store in some variable and i only know about class name starts with tile-position.

my object structure is like this.

var obj={
     tile-position:""
      }

the tile-position-1-4 keeps getting updated so i dont know last numbers but what i know is that it starts with tile-position-[1-4]-[1-4].

4
  • you have both your array and object structures wrong. Can you please check those. That array is not the array of objects you are talking about Commented May 26, 2018 at 6:08
  • your object will contain only 1 key always? Commented May 26, 2018 at 6:17
  • my array contains a set of string and i want a particular string from array and gets store in object obj.tile-position but thing is i don't know string what i know is that it always start with tile-position. Commented May 26, 2018 at 6:18
  • yes @sravan my object contain only one key. Commented May 26, 2018 at 6:19

2 Answers 2

1

Here is the required solution:

Steps:

  1. First the array and the object are taken.
  2. Next we fetch the key of the object.
  3. Next we search the substring of the key from the array
  4. Next, we add that string from array into the value of that object

var foundString = "";
var arr = ["tile", "tile-2", "tile-new", "tile-position-1-4"];
var obj = {   'tile-position':""  }
var key = Object.keys(obj)[0];
for(i = 0; i < arr.length ; i++){
  if(arr[i].indexOf(key) > -1){
    obj[key] = arr[i]
  }
}
alert(JSON.stringify(obj));
var string_obj = JSON.stringify(obj);
document.getElementById("demo").innerHTML = string_obj;
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <p id="demo">Hello!</p>
  </body>

</html>

Here is a working DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

Do create object like:

var obj = {
    "tile: : "tile",
    "tile-2" : "tile-2",
    "tile-new" : "tile-new", 
    "tile-position-1-4" : "tile-position-1-4"
}

I think you do not have problem with it. Then you're able to get it as var res = obj["tile-position-1-4"].

P.S. Sorry, probably I do not understand correctly structure of your boject.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.