Map object to another object javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Let's say we get an object like this
let formA = {
"a1": 1, "b1":2, "c1":3,
"a2": 11, "b2":12, "c2":13,
"a3": 21, "b3":22, "c3":23
}
And what we have is
let formB = {
"a1": 0, "b1":0, "c1":0,
"a2": 0, "b2":0, "c2":0
}
And the result must be
let result = [
{"a1": 1, "b1":2, "c1":3, "a2": 11, "b2":12, "c2":13}, // Form B
{"a1": 21, "b1":22, "c1":23, "a2": 0, "b2":0, "c2":0} // Form B
]
Once the given object properties gets filled up, it must create a new object for the remaining mapped like series.

Builds an array that holds the number of formB shaped objects needed to contain all values of formA.
Builds [key,value] pairs by filling in the values using values from formA in groups of values of the number of formB's key/values. Turns it into an Object using fromEntries.
let formA = {
"a1": 1, "b1":2, "c1":3,
"a2": 11, "b2":12, "c2":13,
"a3": 21, "b3":22, "c3":23
}
let formB = {
"a1": 0, "b1":0, "c1":0,
"a2": 0, "b2":0, "c2":0
}
const keys = Object.keys(formB)
const values = Object.values(formA)
console.log(
// build array that is formA.size/formB.size rounded up, map values
Array(Math.ceil(values.length/keys.length)).fill().map((obj,i) =>
// build object using keys from formB, with values from formA
Object.fromEntries(keys.map((key,j)=>[key,values[i*keys.length+j]||0])))
)

Your post isn't clear, but I think you're trying to just merge two objects into one.
This can be done with the es6 spread operator. Here is the MDN docs for the spread operator.
Here is an example I wrote to show how you can use the spread operator to merge two objects and then log the key/values of the merged object:
let object1 = {
firstKey: 'firstValue',
secondKey: 'secondValue'
};
let object2 = {
secondObjectKey: 'secondObjectValue'
}
let mergeObjects = {...object1, ...object2};
for (const [key, value] of Object.entries(mergeObjects)) {
console.log(`${key}: ${value}`);
}
You can also view the example in code sandbox.

Related

what is the best way to push an array of objects into an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is the array of objects that is to be push to an array
[{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
How to achieve this array below from the above
"array": [
[
[
11,
21
],
[
31,
41
],
[
10,
20
]
]
]
Use Array.prototype.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
Map it
let arr = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
let result = [arr.map(({a,b}) => [a,b])];
console.log(result);
Use reduce to form an array and then Object.values to extract the object prop values for each sub array.
const arr = [{
a: 11,
"b": 21
}, {
"a": 31,
"b": 41
}, {
"a": 10,
"b": 20
}];
const result = arr.reduce((acc, x) => {
const values = Object.values(x);
acc.push(values);
return acc;
}, [])
console.log({
array: result
});
[].concat(array.map((val)=>Object.values(val)))
If all you want to do is push each element of B into A you can do A.concat(B).
If you want to make a new array with all the values your can
c = ([]).concat(A,B)
For your array of objects with values, you could
c = []; for ( vals in b ) c.concat(Object.values(vals);

How to Count Unique Arrays in a Multidimensional Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am looking for a way to not only find unique arrays within a multidimensional array, but also count how many times a particular array occurs.
For Example
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
// Code
???
// Results
uniqueArrays === [[1,2], [1,3], [1,4]]
theCount ==== [2, 1, 3]
Edit:
I didn't realize that I had to show my attempts of how I should solve a problem before I asked a question.
I do know how to count the length of an array use the length() method. I do know how to filter unique arrays from a multi-dimensional array. I did not post my attempts using those tools though because those two issues have been solved to death.
You can map each inner array to a stringified version of itself using .map(JSON.stringified). Now, using this new array, you can reduce it to an object which contains each stringified array as a key, and keeps the number of occurrences as its value. While reducing, you can check whether or not the object's key has already been set using a[k] = (a[k] || 0)+1. If it has already been set, it will use the current number stored at the key and increment it by 1, if it hasn't already been set it will set it equal to zero, and then increment it by 1 (which acts as the default value for any new keys (i.e newly seen arrays)).
Lastly, you can get the keys from your object which represent each unique array as strings using Object.keys(), and parse each back into a non-stringified array using JSON.parse. You can get the counts from your array by using Object.values() as this will get all the values (ie: the counters) of your reduced object and put them into an array.
See example below:
const arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
const arr_str = arr.map(JSON.stringify);
const arr_map = arr_str.reduce((a, k) => (a[k] = (a[k] || 0) + 1, a), {});
const uniqueArrays = Array.from(Object.keys(arr_map), JSON.parse);
const theCount = Object.values(arr_map);
console.log(uniqueArrays);
console.log(theCount);
you can use below code
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
var test = [], obj ={};
arr.forEach(val => {
if(test.indexOf(val.toString()) == -1){
test.push(val.toString());
obj[val.toString()] = 1;
uniqueArrays.push(val);
}else{
obj[val.toString()] += 1;
}
})
theCount = Object.values(obj);
console.log(uniqueArrays);
console.log(theCount);
Hope it will help you.

How to count the frequencies of elements in an array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Assuming you have an array x = [1, 1, 2, 2, 2, 3], and you had to output a sorted array of objects containing a key-value pair (where the key represents the element, and the value the frequency) like:
y = [
{
2: 3
},
{
1: 2
},
{
3: 1
}
]
The resulting array should be sorted by the values.
What would be the best way of doing this?
You can create a temporary object and do simple .forEach and check if current number exists in object as key, if true plus 1 to the value, otherwise create that key, then with simple .map add all key value pairs in separate object in new array
const x = [1, 1, 2, 2, 2, 3];
const k = {};
x.forEach(v => {
if(k[v]) {
k[v] +=1;
} else {
k[v] = 1;
}
});
const y = Object.keys(k).sort((t,c) => k[c] - k[t]).map(key => ({[key]: k[key]}));
console.log(y);

Adding a new JSON object in front of JSON array set [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Playing with nodeJs currently and have been trying to write new data into an existing JSON file, only to have problems with the format as well as getting the right data in. I want to get this new JSON obj to the FIRST of the array list. I did this by grabbing the first index ID, increment it, and tried using unshift() but it isn't adding the way I expected.
JSON file content data.json:
[
{
"id": 3,
"content": "three"
},
{
"id": 2,
"content": "two"
},
{
"id": 1,
"content": "one"
}
]
Code I wrote for new JSON obj I want to add:
var allJSON = fs.readFileSync('data.json');
var allj = JSON.parse(allJSON);
var lastId = parseInt(allj[0].id);
var newData = {
id: ++lastId,
content: "test"
};
var allNewJSON = allj.unshift(JSON.stringify(newData));
// this yields a result of just the number "4" and erased everything else.
Array#unshift does not create and return a new array; instead, it modifies the original array and returns its new length. In your case, this value would be 4. I would suggest ignoring the return value of unshift and simply continuing your code using the allj variable, like so:
var allJSON = fs.readFileSync('data.json');
var allj = JSON.parse(allJSON);
var lastId = parseInt(allj[0].id);
var newData = {
id: ++lastId,
content: "test"
};
allj.unshift(newData);
console.log(allj) // modified as desired!
Edit: As was mentioned in the comments above, you probably don't want to be calling JSON.stringify on the object newData before inserting it into your array. At this point you want to be working with JS objects rather than JSON strings.
Your result is due to the way unshift works.
unshift is a function which returns the length of the updated array.
For example
> const a = [10, 20, 30];
> a.unshift(5);
4
That's right, the call to unshift returns 4, because the updated array has 4 elements.
Let's see the updated value of a:
> a
[5, 10, 20, 30]

Optmize flattening of an array of nested json objects in JavaScript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
Supposed to have an array of objects of objects like
[
{
"key_set1": {
int_val: 3,
arr_val: [
1,
3,
4
]
}
},
{
"key_set2": {
string_val: "foo"
}
}
]
I want to flatten inner objects keys to a new root object to get at the end
{
"key_set1": {
"int_val": 3,
"arr_val": [
1,
3,
4
]
},
"key_set2": {
"string_val": "foo"
}
}
Assumed that
This nested structure can have N levels with N > 10
The structure is a valid json object not a javascript object i.e. it has atomit/non atomic types, not function object types;
The whole input json file can be hundreds of KBytes;
The work must be done in JavaScript V8 / ECMAScript6;
The processing time must be of order of milliseconds
A variant of this mapping, needs to parse the input json object and modify the values (like using map array method).
I want to get the most optimized solution for this using built-in methods like forEach and/or fast iterators for, while etc., for the best/worst cases.
As long as I understand it correctly, you like to replace the array with an object and take the first level key as the new key for the result object.
var array = [{ "key_set1": { int_val: 3, arr_val: [1, 3, 4] } }, { "key_set2": { string_val: "foo" } }],
object = {};
array.forEach(function (a) {
var key = Object.keys(a)[0];
object[key] = a[key];
});
console.log(object);
If you "want to get this optimized at its best" - you shouldn't use Array.map in your case as it returns a new array. You just need to iterate fast through the list array and fill the new flattened object. Consider the following "optimized" solution:
var flattened = {}, len = list.length;
while (len--) {
Object.keys(list[len]).forEach((k) => (flattened[k] = list[len][k]));
}
console.log(JSON.stringify(flattened, 0, 4));
The output:
{
"key_set2": {
"string_val": "foo"
},
"key_set1": {
"int_val": 3,
"arr_val": [
1,
3,
4
]
}
}

Categories

Resources