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

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)

Related

JS. Clone object but prefix all values [duplicate]

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}`)

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));

Combine items after mapping from an array to a single object [duplicate]

This question already has answers here:
Flatten array with objects into 1 object
(12 answers)
Closed 2 years ago.
Can you please help me to create object out of array of objects?
Array to convert arr = [{name:'Ryan'}, {surname:'raynold'}]
required output finalObj = {name:ryan, surname:raynold}
I tried to get the result by doing
let objectArr = Object.assign({}, arr);
but result was like this
{ 0: {shoulder: "14"}, 1:{neck: ""} }
This is a good case for Object.assign.
let arr = [{name:'Ryan'}, {surname:'raynold'}]
let finalObj = Object.assign({}, ...arr);
console.log(finalObj);
Object.assign can take multiple objects as arguments, and so you can spread those objects from your input array. The first argument represents the object in which the others are merged.
You could do it with a array reduce like this:
let finalObj = arr.reduce((acc, cur) => ({...acc, ...cur}), {})

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)

is there a syntax in javascript new features where i can extract object values into new object with same key and values? [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(13 answers)
Closed 5 years ago.
let obj = { a: 1, b:2, c:3}
I can do
let {a,b,c} = obj
but i want an object with just 'a' and 'b' as key and same value as in obj
do i have a syntax for that one
it is basically filtering out the keys but do we have some succint syntax for this one because I constantly do
let test = {
a: obj.a,
b: obj.b
}
how about let n = ({a,b} = obj) && {a,b}?
Using object destructuring, Hope this helps
var obj = {"a":1, "b":2, "c":3}
var test = (({a, b}) => ({a, b}))(obj);
console.log(test);
The following does this:
let result = {}
Object.keys(obj)
.filter(e=>![LIST WITH KEYS TO FILTER].includes(e))
.forEach(e=> result[e]= obj[e])
It gets all keys from obj, filters out some keys and pushes the values of the leftover keys to the result object.

Categories

Resources