How to copy key's value in 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 1 year ago.
Improve this question
I have 2 array
var arr = [{ 1: a }, { 2: b }, { 3: d }];
var arr1 = [{ 1: a }, { 2: c }, { 3: e }];
I want to copy arr1 key's value to arr. below I want output result
arr = [{ 1: a }, { 2: c }, { 3: e }];
How it is possible to achieve?

You could assign the objects with the wanted object. The result keeps the object references as well as the array reference.
const
array = [{ 1: 'a' }, { 2: 'b' }, { 3: 'd' }],
update = [{ 1: 'a' }, { 2: 'c' }, { 3: 'e' }];
array.forEach((o, i) => Object.assign(o, update[i]));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you like only to update a certain property, you need to iterate the array and all entries.
const
array = [{ 1: 'a' }, { 2: 'b' }, { 3: 'd' }],
update = [{ 1: 'a' }, { 2: 'c' }, { 3: 'e' }];
array.forEach((o, i) => {
Object.entries(update[i]).forEach(([k, v]) => {
if (o[k] !== v) (console.log(o[k], v), o[k] = v);
})
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Javascript sort object by key within nested objects

I have the following object:
{
4: {
1: [
{ order: 1, name: 'Test 4' }
]
},
0: {
15: [
{ order: 7, name: 'Test 1' },
{ order: 3, name: 'Test 3' },
],
12: {
{ order: 1, name: 'Test 2' }
}
}
}
Essentially what I am trying to achieve is to order this by the keys and then order further by the order property from within the nested value. So in turn I get the following output:
{
0: {
12: {
{ order: 1, name: 'Test 2' }
},
15: [
{ order: 3, name: 'Test 3' },
{ order: 7, name: 'Test 1' },
]
},
4: {
1: [
{ order: 1, name: 'Test 4' }
]
}
}
I then want to completely flatten this so it's without any of the outer object and just the data within the order, the outcome would then be:
[
{ name: 'Test 2' },
{ name: 'Test 3' },
{ name: 'Test 1' },
{ name: 'Test 4' }
]
I imagine this would be some kind of recursive operation which I need to do and I originally did it with something like the following but it got a bit messy:
Object.keys(obj)
.sort()
.reduce((acc, key) => { acc[key] = obj[key]; return acc; }, {});
Anotner one sorting approach
const obj = {4:{1:[{order:1,name:'Test 4'}]},0:{15:[{order:7,name:'Test 1'},{order:3,name:'Test 3'},],12:[{order:1,name:'Test 2'}]}};
const result = Object.entries(obj).flatMap(([u1, v1]) =>
Object.entries(v1).flatMap(([u2, v2]) =>
v2.map((v3) => ({ key: u1*1_000 + u2 + v3.order/1_000, item: v3 }))
)
)
.sort(({ key: a }, { key: b }) => a - b)
.map(({ item }) => item);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
You can sort each obj by keys using Object.keys(obj).sort() and then access each element by its key.
Do this 2 times to get the array of object
const obj = {
4: {
1: [
{ order: 1, name: 'Test 4' }
]
},
0: {
15: [
{ order: 7, name: 'Test 1' },
{ order: 3, name: 'Test 3' },
],
12: [
{ order: 1, name: 'Test 2' }
]
}
}
let flatItems = []
const keys = Object.keys(obj).sort()
for (const key of keys){
const subObj = obj[key]
const subKeys = Object.keys(subObj).sort()
for(const subKey of subKeys){
flatItems = flatItems.concat(subObj[subKey].sort((a, b) => a.order - b.order))
}
}
console.log(flatItems)
The integer properties (in the range of 32 bit unsigned integers) don't need sorting, as iteration over them (e.g. via Object.values) is by specification already sorted by those integer keys. So the logic needs to focus only on sorting the inner objects, and it will be fine.
const flatSort = obj => Array.isArray(obj)
? [...obj].sort((a, b) => a.order - b.order).map(a => a.name)
: Object.values(obj).flatMap(flatSort);
const obj = { 4: { 1: [ { order: 1, name: 'Test 4' } ] }, 0: { 15: [ { order: 7, name: 'Test 1' }, { order: 3, name: 'Test 3' }, ], 12: [ { order: 1, name: 'Test 2' } ] } };
const res = flatSort(obj);
console.log(res);
Object keys can’t easily be sorted, the iteration order depends on different rules and isn’t straightforward to work with. As a result you’re better off converting your object into an array of key-value pair arrays (entries), and then sort that array rather than trying to sort your object (sorting is required as your object can have non-array index keys such as -1).
To do this, you can create a recursive function (sortEntries) that takes your object and grabs the entries from it. Using the key component of the entries, you can sort based on that. Once you've sorted the entries, you can .flatMap() the result of recursively sorting your nested object value by calling the sortEntries function again. For the base case (termination case), you can stop the recursion once you've found a value that is an array, which for that you can sort by the order property for your objects and then .map() each object to extract only the name property. Each array returned by .map() will be merged together into one resulting array due to the previous .flatMap() call:
const obj = { 4: { 1: [ { order: 1, name: 'Test 4' } ] }, 0: { 15: [ { order: 7, name: 'Test 1' }, { order: 3, name: 'Test 3' }, ], 12: [ { order: 1, name: 'Test 2' } ] } };
const sortEntries = (obj) => {
return Array.isArray(obj)
? obj.slice().sort((a, b) => a.order - b.order).map(({name}) => ({name}))
: Object.entries(obj).sort(([a], [b]) => a - b).flatMap(([, val]) => sortEntries(val));
}
const res = sortEntries(obj);
console.log(res);
Full Key/Value object sorting (array values included):
function sortKeys(object) {
if (Array.isArray(object))
return object.sort().map((obj) => (typeof obj === "object" ? sortKeys(obj) : obj));
const sortedObj = {};
const keys = Object.keys(object).sort();
for (var index in keys) {
const key = keys[index];
if (typeof object[key] === "object") {
sortedObj[key] = sortKeys(object[key]);
} else {
sortedObj[key] = object[key];
}
}
return sortedObj;
}

How can I get an array of all possible combinations of an object's key/values [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 9 months ago.
Improve this question
I have an object:
{
a: 1,
b: "2",
c: "3",
// ...
}
I want to get an array with all possible combinations, as objects, of each key/value pair like this:
[
{ a: 1 },
{ b: "2" },
{ c: "3" },
{ a: 1, b: "2", c: "3" },
{ a: 1, b: "2" },
{ a: 1, c: "3" },
{ b: "2", c: "3" },
// ...
]
You could treat the object's keys like a set, and calculate its power set using an algorithm like the one described in this question:
const fn = (o) => {
const result = [];
const keys = Object.keys(o);
for (let i = 0; i < Math.pow(2, keys.length); i++) {
let current = {};
for (let j = 0; j < keys.length; j++) {
if ((i & (1 << j)) > 0) {
current[keys[j]] = o[keys[j]];
}
}
result.push(current);
}
return result;
}
console.log(fn({a: 1, b: '2', c: '3'}));

Problem with map function and for loop. Why is the result always "8"?

I have a problem with this code. For every item in editorJSON, I want to access the id of the previous question and return it as "inputcontext" (e.g., for Question id 2 I want to access Question id 1, etc.). I tried to implement this with the following code, but the console.log() command always gives me "8".
const editorJSON = {
1: {
id: 1,
name: "Question"
},
2: {
id: 2,
name: "Question"
},
3: {
id: 3,
name: "Tipp"
},
4: {
id: 8,
"name": "Question"
}
}
Object.keys(editorJSON).map((key, index) => {
const inputcontext = () => {
let inputcontext = "";
var l = Object.keys(editorJSON).length;
for (i = l; l < 1; i--) {
if (editorJSON[i].name === "Question") {
let inputcontext = editorJSON[i].id;
return inputcontext
}
}
}
console.log(inputcontext())
})
You could filter the keys of the object and map the previous found key. This approach relies on the order of the keys with index like keys (32 bit positive integer numbers).
const
data = { 1: { id: 1, name: "Question" }, 2: { id: 2, name: "Question" }, 3: { id: 3, name: "Tipp" }, 4: { id: 8, name: "Question" } },
previousQuestions = Object
.keys(data)
.filter(k => data[k].name === 'Question')
.map((k, i, a) => [data[k].id, data[a[i - 1]]?.id]);
console.log(previousQuestions);
Since numeric keys are always iterated over in ascending order, you can loop over previous elements until reaching a question using Array#map which provides the original array as the third argument to the callback.
const editorJSON = {
1: {
id: 1,
name: "Question"
},
2: {
id: 2,
name: "Question"
},
3: {
id: 3,
name: "Tipp"
},
4: {
id: 8,
"name": "Question"
}
};
const res = Object.keys(editorJSON).map((key, index, arr) => {
let inputcontext;
for(let i = key - 1; i > 0; i--){
if(editorJSON[i]?.name === "Question"){
inputcontext = editorJSON[i].id;
break;
}
}
return {...editorJSON[key], inputcontext};
});
console.log(res);

How to split array into three arrays by index? [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 2 years ago.
Improve this question
I have an array of 9 elements(maybe more).
I need to split by indexes into three arrays.
const array = [{id: 0}, {id: 1}, ..., {id: 8}];
I want to recieve 3 array like that:
const array0 = [{id: 0}, {id: 3}, {id: 6}];
const array1 = [{id: 1}, {id: 4}, {id: 7}];
const array2 = [{id: 2}, {id: 5}, {id: 8}];
You could take the remainfer of the index with three and address the dame group for every third element.
If necessary take destructuring assignment, like
[array0, array1, array2] = result;
const
array = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }],
result = array.reduce((r, o, i) => ((r[i % 3] = r[i % 3] || []).push(o), r), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can filter() the array using remainder operator %. For array1 check if the id % 3 === 0 and id % 3 === 1, id % 3 === 2 for next ones respectively
const array = Array(9).fill().map((x, i) => ({id: i}));
const array1 = array.filter(x => x.id % 3 === 0);
const array2 = array.filter(x => x.id % 3 === 1);
const array3 = array.filter(x => x.id % 3 === 2);
console.log('array1', array1)
console.log('array2', array2)
console.log('array3', array3)

How to implement complex arrays? [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 3 years ago.
Improve this question
For example, when id is equal to 1, an array is ['a', 'b'], and when id is equal to 2, another array is ['c']. The result of these two arrays is [["a","b "],["c"]]
I want the results as follows:
[["a","b"],["c"]]
my code:
var data = [{
id: 1,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
}
]
Using reduce:
var data = [{
id: 1,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
}
]
let result = data.reduce((acc, item) => {
return item.id === 1 ? acc[0].push(item.name) : acc[1].push(item.name), acc
},[[], []])
console.log(result)

Categories