JS. Clone object but prefix all values [duplicate] - javascript

This question already has answers here:
How to add prefix to array values?
(5 answers)
Closed 7 months ago.
Let's say there's an object with string values:
const A = { key_a1: "value_a1", key_a2: "value_a2" };
What is the way to clone this object and add some prefix to the values? So I want to convert object A into object B that looks next:
const B = { key_a1: "prefix_value_a1", key_a2: "prefix_value_a2" };
I know about copy syntax like const B = { ...A } but that does not allow to modify values.

You can use Object.entries to turn the keys and values of the original object into an array, and reduce to create a new Object with the same keys of the original object with a prefix.
const A = { key_a1: "value_a1", key_a2: "value_a2" };
const B = Object.entries(A).reduce((acc, [key, value]) => ({
...acc,
[`prefex_${key}`]: value
}), {})
console.log(B)

You can loop over it's values, like:
Object.values(A).map(i => `prefix_${i}`)

Related

Fill Out Array of Objects to add 0 values [duplicate]

This question already has answers here:
Make array objects all have the same keys
(5 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have a dynamic array which for downstream purposes needs to have all properties define for all objects.
If I have this array:
[
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
]
How do I fill it out to infill zero values for properties where they exist elsewhere in the array, but not in that object.
Essentially I need to up with this:
[
{"Header":"1","Apples":10, "Oranges":0, "Pears":0},
{"Header":"2","Apples":10, "Oranges":153, "Pears":0},
{"Header":"3","Apples":0, "Oranges":280, "Pears":200},
{"Header":"4","Apples":0, "Oranges":1165,"Pears":0}
]
Header property is essentially the id of each object
const arr = [
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
];
// get unique keys
let objWithAllProp = arr.reduce((acc, item) => ({...acc, ...item}));
// Get keys as an array and Create an object with all keys set to the default value to 0
let uniqueObjectWithAllProp = Object.keys(objWithAllProp).reduce((acc, key) => {
acc[key] = 0
return acc;
}, {});
// Replace all default values with original, so if key not present in original item, it will be available from uniqueObjectWithAllProp and value default to 0
let result = arr.map((item) => ({...uniqueObjectWithAllProp , ...item}));
console.log(result);
You can get all the existing property values by pushing each item's properties to an array (with Object.keys), then using Set and spread syntax to get the unique.
Then, map over each item in arr and in the loop, loop through the existing property values and check whether the current item has that property. If not, set the value of that property to 0.
const arr = [
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
]
const properties = [...new Set(arr.map(e => Object.keys(e)).flat())]
const result = arr.map(e => (properties.forEach(f => !e.hasOwnProperty(f) ? e[f] = 0 : ''), e))
console.log(result)

How to remove dublicate values from array of objects using javaScript? [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));

Convert array to object keys [duplicate]

This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)

Sort Javascript Object by Value [best practices?] [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 5 years ago.
Since there's no official way to sort an object by values, I'm guessing you either (1) Use an array instead or (2) Convert your object to an array using Object.entries(), sort it, then convert back to an object. But option (2) is technically unsafe since Javascript objects aren't supposed to have order.
Now I have a React app where I'm using Redux. I'm storing my data not as an array but as an object iterated by id values. This is what Redux suggests, and I would do it anyways, because of lookup times. I want to sort this redux data, so what I'm currently doing is option (2) of converting to array and then back to object. Which I don't really like.
My question is: Is this what everyone else does? Is it safe to sort an object?
Example:
const sortObject = (obj) => {
//return sorted object
}
var foo = {a: 234, b: 12, c: 130}
sortObject(foo) // {b: 12, c:130, a:234}
this is what I'm currently doing.
My object data structure looks something like this
obj = {
asjsd8jsadf: {
timestamp: 1234432832
},
nsduf8h3u29sjd: {
timestamp: 239084294
}
}
And this is how I'm sorting it
const sortObj = obj => {
const objArray = Object.entries(obj);
objArray.sort((a, b) => {
return a[1].timestamp < b[1].timestamp ? 1 : -1;
});
const objSorted = {};
objArray.forEach(key => {
objSorted[key[0]] = key[1];
});
return objSorted;
};
If you are using the Redux documentation for reference you should also have an array with all of the id's in it. Wouldn't it be easier to just sort that array and then use insertion sort when you add something to the state. Then you could use the sorted array to access the byId property of the state?

JS: Convert An Array Into An Object Without Indexes [duplicate]

This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)

Categories

Resources