Push Duplicate key data on key array in javascript - javascript

I have this data structure. I have used the underscorejs but could not find way to that like the below structure
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
var groupArr = [];
##loop through the data##
data.forEach(function(item){
##find the keys ##
var keys = Object.keys(item);
var obj = {};
obj[keys] = [];
##push the data to object keys array##
obj[keys].push(item[keys])
groupArr.push(obj)
})
By using this data structure I want something like this structure
[{"5+":[2,1,3]},{"3-5":[0,1,0]},{"1-3":[1,0,,3]},{"0.5":[0,0,0]},{"<30":[0,0,0]}]
As I have tried everything but could not find the solution any help would be highly appreciated.

The first part converts the list of objects to a single object, where the keys are each of the unique keys from the list of objects and the values for each key are joined as an array:
{
"5+": [2,1,3],
"3-5": [0,1,0]
...
}
Since this is not the format you wanted, the second part converts this object into a list of objects by looping over each key and creating a new object from it.
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
// create object with all the values joined together in lists.
var map = data
.reduce(function (map, obj) {
var key = Object.keys(obj)[0];
// checks if the key allready exits in the new object.
// If it does we push a new value into the array,
// otherwise we create a new property with a list with one value.
map[key] ?
map[key].push(obj[key]):
map[key] = [obj[key]];
return map;
}, {});
// convert above result to a list with objects.
var newFormat = Object.keys(map)
.map(function (key) {
var obj = {};
obj[key] = map[key];
return obj;
})
console.log(newFormat)

Related

How to Convert an Array into Object of key value pair

I need to convert an array into object with key values.For Example
var Array = [17.3850, 78.4867]
I need to convert into Object in this manner
var Object = {"lat":17.3850, "lng":78.4867}
Using Array.prototype.map() make an iteration over the array, create an array of Object and finally convert that to an object using Object.assign().
var key = ['lat', 'lng'];
var array = [17.3850, 78.4867]
var obj = Object.assign({}, ...key.map((e, i) => ({[e]: array[i]})))
console.log(obj)
You could map an array with arrays of key/value pairs and create an object with Object.fromEntries.
var array = [17.3850, 78.4867],
keys = ['lat', 'lng'],
object = Object.fromEntries(array.map((v, i) => [keys[i], v]));
console.log(object);
you can use the constructor in JavaScript.
class Location {
constructor(lat, lng) {
this.lat = lat,
this.lng = lng
}
}
var myArray = [17.3850, 78.4867];
var myLocation = new Location(myArray[0], myArray[1]);
myLocation.lat;
myLocation.lng;
Instead of myArray[0] & myArray[1] you can use loop to make it dynamic.

Pushing data into an array within a 2d array at specific index

var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
arr now looks like this -> [key, Array(1)]
New data comes into barr how to i push another item into the nested array for the same key?
expected output should be something like this: [key, Array(2)]
Option #1:
You can push into the barr array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
barr.push('key2', 'key3');
console.log(arr);
barr is a reference to the array, and when you pushed it into your arra array you actually put there the reference, so when updating barr your reference is still there (and updated).
Option #2:
You can push into the array that is in the 2nd place of your array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
arr[1].push('key2', 'key3');
console.log(arr);
The way you did it the "key" is actually just another value in the array (at index 0). If you want to use a string as the key you'll have to use an object. You can set and get properties using the bracket syntax. The bracket syntax works with arrays as well, but only using integers as keys.
var obj = {};
var barr = [];
var key = "key1";
obj[key] = barr;
// barr changed
obj[key] = barr;

Creating a two-dimensional object from a string of values

In JavaScript, how would I create a two-dimensional object from a string of values, in which the first value would be the name, the last is the content, and all other values in between are properties?
For example, I have a string "capitals,Asia,China,Beijing" and I want the code to split this string into four values and create an object capitals["Asia","China"] = "Beijing";.
How could I do that?
In a complete code piece that would look like this:
<script>
Values = "capitals,Asia,China,Beijing";
Values = Values.split(",");
alert(capitals["Asia","China"]);
</script>
I want the alert box to show me the word Beijing.
How could I do that?
JavaScript does not have two-dimensional arrays or objects that you can access using array[index1, index2] as in some other languages. To do this, you have to use nested objects/arrays, such as
capitals["Asian"]["China"]
To create these, you can do something like:
function makeEntry(obj, str) {
const parts = str.split(','); // array of comma-delimited values
const value = parts.pop(); // final value ("Beijing")
const final = parts.pop(); // final property ("China")
// Find nested property, creating empty object if not there.
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!(parts in obj)) obj[part] = {};
obj = obj[part];
}
// Set final value.
obj[final] = value;
}
const data = {};
makeEntry(data, "capitals,Asian,China,Beijing");
console.log(data);
console.log(data.capitals["Asian"]["China"]);
This code will work even if there are more levels, such as "capitals,Asia,East Asia,China,Beijing".
Note that there is no way to create a variable in JS given a name. Therefore, we provide an initial object, and build the nest structure within it.
Another approach
Another approach is to create a single-level object with keys such as "capitals,Asian,China". That's easier to create, but might be more inconvenient to access. For example, there would be no easy way to find all the Asian capitals. Below, I'm using regexp to pick apart the input into the first part and the final value.
function makeEntry(obj, str) {
const [, key, value] = str.match(/(.*),([^,]+)$/);
obj[key] = value;
}
const data = {};
makeEntry(data, "capitals,Asian,China,Beijing");
console.log(data);
console.log(data["capitals,Asian,China"]);
You can use WeakMap to set the key of the WeakMap object to an object; Array.prototype.shift(), Array.prototype.splice(), Array.prototype.pop() to set the value of the WeakMap object instance.
let Values = "capitals,Asian,China,Beijing";
Values = Values.split(",");
const capitals = {[Values.shift()]:Values.splice(0, 2)};
const wm = new WeakMap;
wm.set(capitals, Values.pop());
console.log(wm.get(capitals));
You can alternatively set the property of an object to the result of JSON.stringify() called on Values.splice(1, 2)
let Values = "capitals,Asian,China,Beijing";
Values = Values.split(",");
const key = JSON.stringify(Values.splice(1, 2));
console.log(key);
const map = {[Values.shift()]:{[key]:Values.pop()}};
console.log(map.capitals[key]);

Convert Array of Javascript Objects to single simple array

I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.
Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]
How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});

JSON.stringify(object) incorrect

Sorry for my last question being so confusing, I was confused my self, but now I got a proper example:
var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";
var jsonStr = JSON.stringify(jsonObj);
// {"entities":[]}
console.log(JSON.stringify(obj));
The output of JSON.stringify(obj) is wrong as you can see.
What causes this ?
You're first building an array ([]), then assigning properties to it with non-number keys (player). This is technically possible (as in not causing an error), but it's not what arrays are for.
You should use objects ({}) instead. Also, ["player"] is the same as .player.
var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";
Objects can take any property key. Arrays are a subset of objects, which should only have indices (numbers >= 0) as keys.
Your life would be much easier if you'd define your objects in JSON to begin with:
var obj = {
'entities': [
{'player':{'pos': '0,0'}}
]
};
You're using named array indeces instead of object key/value pairs.
var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";
// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
entities, and entities["player"] and entities["player"]["0"] need to be objects, not arrays.
You're adding properties to these arrays, rather than pushing values onto them. These custom properties are not getting stringified.
The fix is simple:
var obj = {};
obj.entities = {}; // <------------ this is an object now
obj.entities["player"] = {}; // <--------- also an object
obj.entities["player"]["0"] = {}; // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
I think you have some serious confusions about arrays and objects in javascript. An array ([]) works only with positive integer indexes. In your example you are doing the following:
obj.entities = [];
obj.entities["player"] = [];
You say that obj.entities is an array and then you use player as index. And player is not an integer. So this code makes no sense. On the other hand you could use objects with properties. Those properties can be strings:
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
You are confusing objects with arrays. The following code will work.
var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";
The things you went wrong:
An array can have only integer indexes. So it's incorrect writing a["1"] if you intend to use a as an array.
To be correctly serialized, only an object can have named properties, like object.entities.player or object.entities["player"].

Categories

Resources