0

I am trying to wrap my head around how I might accomplish something like this, structurally:

var keywordDataProducts = 
      [
            {"keyword" : "keyword1", "list" : [ "DP1", "DP2" ] },
            {"keyword" : "keyword2", "list" : [ "DP1" ] } 
      ];

But of course, without the values being hard coded. For instance, we currently loop through all the DP values (DP1, DP2, DP3, etc..) - which all have 0-M keywords. I'm trying to create an inverse lookup of that, where you can get all DPs that use a particular keyword. I have code that uses the structure above perfectly, but I just need the data to get populated more dynamically.

Do I initialize the var keywordDataProducts = []; declaration with anything in it, or define the structure of it having a keyword and a list (which is an array)? Or do you leave it as an array with nothing about it, and define that when you're adding items?

I've heard associative arrays can be used for a situation like this, but I'm not quite wrapping my head around that at the moment. I've also seen objects with {} usages, but there is no push there and I need an array of keywords, which also contains arrays of DPs (list). Thoughts?

4
  • Think of how you'd do it with paper and pencil. Iterate through the array and build a map of keywords to "DP" lists. Commented Jan 20, 2017 at 14:53
  • Give us an input and output example. Commented Jan 20, 2017 at 14:56
  • could be helpful ... Commented Jan 20, 2017 at 14:57
  • 1
    A javascript object is an associative array. Commented Jan 20, 2017 at 15:08

3 Answers 3

1

You would do something like this, but you didn't clearly describe what the input look like and what output you're looking for.

function fn (input) {
  var ouput = {};
  input.forEach( function (DP) {
    for (prop in DP) {
      if (DP.hasOwnProperty(prop) {
        if (output[prop]) {
          output[prop].push(DP);
        } else {
          output[prop] = [DP];
        }
      } 
    }
  });
  return output;
}

This takes this kind of input

[{"alpha":...}, {"beta":..., "delta":...}, {"alpha":..., "gamma":...}]

and returns

{"alpha":[{"alpha":...}, {"alpha":..., "gamma":...}]}, "beta":{"beta":..., "delta":...}, "delta":{"beta":..., "delta":...}, "gamma":{"alpha":..., "gamma":...}}
Sign up to request clarification or add additional context in comments.

Comments

1

I don't know how you want your output so I just made an object with each keyword as its own key for the DP values.

var data = [{dp: "dp1", keys: ["key1", "key2", "key3"]}, {dp: "dp2", keys: ["key1", "key2", "key3"]}, {dp: "dp3", keys: ["key1", "key2", "key3"]},];

function keyWordArray(arr) {
	var newObj = {};
  arr.forEach((obj) => {
  	obj.keys.forEach((keyVal) => {
    	if(newObj.hasOwnProperty(keyVal)){
      	newObj[keyVal].dp.push(obj.dp);
      } else {
      	newObj[keyVal] = {dp:[obj.dp],};
      }
    });	
  });
  return newObj;
}

document.getElementById("data").innerHTML = JSON.stringify(keyWordArray(data));
<div id="data">
</div>

Comments

1

You can treat objects as associative arrays, and you don't have to use "push" to add a new element.

// Create your object like this
var keywordDataProducts = 
{ 
    "keyword1" : { "list" : [ "DP1", "DP2"] },
    "keyword2" : { "list" : [ "DP1" ] }
};

// Treat it like an associative array
var keyword1 = keywordDataProducts["keyword1"];
alert("keyword1 = " + keyword1.list.join(", "));

// Add to it like this
keywordDataProducts["keyword3"] = { "list" : ["DP3", "DP4"] };

// See the new object includes your new keyword
alert(JSON.stringify(keywordDataProducts));    

// To iterate the keys of your object, you can do something like this
for(var item in keywordDataProducts)
{
    if(keywordDataProducts.hasOwnProperty(item))
    {
        alert(item);
    }
}  

You can see the fiddle here; https://jsfiddle.net/gksjtwr6/2/

2 Comments

One small followup to this - I imagine there is a way to loop through each and every entry and pull out all keywords and their list vals as well? In the example above, we stringify it, and we access single ones like "keyword1" - but is there a way to go through every one of them, since it isn't technically an array with {} but rather an object treated as an associative array? Edit - looks like you can maybe do that with .forEach()? Trying some things now
I updated the answer, to include an example of this. You can iterate over it with a for loop as seen above for(var item in keywordDataProducts).

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.