Convert array of data into an object with properties [duplicate] - javascript

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 1 year ago.
How do I convert an array into an object with properties:
With the following data:
["Test Scenario ID", "Login-1"]
I would like to return an object with properties:
{1: "Test Scenario ID", 2: "Login-1"} // desired result
With the following, It maps the data into separate objects, but I would like it to be properties of a single object instead of an array of objects:
row.values.map( (e,i) => { return {i: e} })
[{1: "Test Scenario ID"}, {2: "Login-1"}] // the current result

One option is to use Object.fromEntries to turn an array of entries into the object.
const result = Object.fromEntries(
row.values.map((e, i) => [i, e])
);
Another option is to take your array of multiple objects and put it through Object.assign to combine them.
const result = Object.assign(
...row.values.map( (e,i) => ({i: e}))
);

you can use this:
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The Object.assign() method copies all enumerable own properties from
one or more source objects to a target object. It returns the modified
target object.
you can read more about it here on MDN

Related

Why does the copy of an array using the spread operator when run through map modify the original array?

Why does the copy of an array using the spread operator when run through map modify the original array?
What should i do here to not mutate the original array?
const data = {hello : "10"};
const prop = [{name : "hello", color: "red", value : ""}]
const copyProp = [ ...prop ]
copyProp.map(el => {
el.value = data[el.name] || ""
return el
}) //
console.log(copyProp === prop) // -> false
console.log(copyProp) // -> value: 10
console.log(prop) // -> Value: 10 (Should still be "")
The spread operator creates shallow copy of the array. In other words, you create a new array with references to the same objects. So when you modify those objects, the changes are reflected in the original array.
In general, when you need copy an array, you should consider making a deep copy. However, in this case, you just need to use map() correctly. map() creates a new array, so it can make the modified copy for you directly:
const copyProps = props.map(el => {
return {
...el,
value: data[el.name] || '',
}
});
Here I copy each object using the spread operator. This means the resulting array has its own references of objects. This has the same caveat as your original solution: this is a shallow copy. For your example data, it is fine because all values and keys are strings. However, if your real data is more deeply nested with more arrays and objects, you will encounter the same problem.
Both arrays and objects are passed by reference, so when you spread an array you create new array but fill it with references to original objects and when you modify those objects in the new array you still modify the same data in memory that is referenced in both arrays.
Also map method will always return new array so in this case you only need to clone objects and since here you do not have deeply nested objects you can use object spread syntax.
const data = {
hello: "10"
};
const prop = [{
name: "hello",
color: "red",
value: ""
}]
const copyProp = prop.map(el => ({ ...el,
value: data[el.name] || ''
}))
console.log(copyProp)
console.log(prop)

Assign javascript array to list of JSON objects with a property name? [duplicate]

This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
Closed 3 years ago.
I would like to convert a javascript array which looks like:
['https://www.google.com', 'https://www.facebook.com']
to a list of JSON objects that looks like this:
[{"redirectUri": "https://www.google.com"},
{"redirectUri": "https://www.facebook.com"}]
I have tried using Object.assign({}, array);
however this retuns json with the parameter name as the index of the array value and are all in a single object:
{"0": "https://www.google.com", "1": "https://www.facebook.com"},
is there a way to change this to use a custom parameter name dynamically?
You just need to map your elements respectively, using Array.map() method:
let result = arr.map(o => {
return {
"redirectUri": o
}
});
Demo:
let arr = ['https://www.google.com', 'https://www.facebook.com'];
let result = arr.map(o => {
return {
"redirectUri": o
}
});
console.log(result);

filter an array of objects based on matching key/value property? [duplicate]

This question already has answers here:
javascript filter array of objects
(8 answers)
Closed 4 years ago.
This is the issue Im trying to solve. I know how to do direct comparison with objects, but Im caught how to make an either or property comparison inside a filter fx.
// tasks are objs with {name: string,id: int}
const taskArray = [task1, task2, task3, task3];
// f(x) needs to take obj param and see if it matches either/or with
// any task obj k/v pair
// my implementation so far, missing something important, help here
const filterTasks = (taskArray, obj) => {
taskArray.filter( task => Object.keys(task) // i know I have to do some equality opperator here but stuck
return taskArray;
}
There it is.
filterTasks will return an array that contains only tasks in the passed array that match at least 1 key/val pair in the passed object.
tArr = [{name: "hi",id: 1},{name: "hola",id: 2},{name: "hello",id: 3},{name: "bye",id: 4}];
const filterTasks = (taskArray, obj) => taskArray.filter( task => Object.keys(task).some( key => obj[key] && obj[key]==task[key]));
console.log(filterTasks(tArr,{name:"hi",id:2}));

React - convert object into array of objects with properties

I have the following object
"data":{
"name 1":"a",
"name 2":"b",
"name 3":"b",
},
How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render compoents for each one passing in the both the name and data?
If you use a reduce function you can do the following to achieve your goal
Object.keys(data).reduce((array, key) => {
return [...array, {key: data[key]}]
}, [])
Reduce is a cool function that iterates and combine data into one single item (could be 1 object, array, integer, etc).
Object.keys() is a way to get each key from the current object and be able to iterate over each.
The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
so you can try something like this
let result = Object.entries(data);
result.map((item, index)=>{
console.log('key is:- ', item[0], ' and value is:- ', item[1]);
});
you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.
This will convert to array of objects that will keep both the name and data.
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
}
var res = Object.keys(data).map(function(name){
var obj = {};
obj[name] = data[name];
return obj;
});
console.log(res);
js native method u can use;
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
};
var newObj = [...Object.values(data), ...Object.keys(data)]
console.log(newObj)

spread operator converting objects to array

I'm trying to convert a data structure like this:
data = {
0:{A:a},
1:{B:b},
2:{C:c},
}
into a structure like this:
[
{0:{A:a}},
{1:{B:b}},
{2:{C:c}},
]
Using the spread operator like this: [...data] returns any empty array.
I also tried [{...data}]
Is there a way to use the spread operator to get the desired result? Also, why doesn't this approach work?
"Is there a way to use the spread operator to get the desired result?" Short answer, no. (see below for alternate solution to what you're trying to accomplish)
"Also, why doesn't this approach work?"
It doesn't work because according to the MDN docs
"The Rest/Spread Properties for ECMAScript proposal (stage 3) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object."
Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.
Alternative solution:
You can do this fairly easily with Object.keys().map(). Object.keys() will get an array of the keys of the object, and Array.map() will map them into an array of the desired structure, like so:
var data = {
0:{A:"a"},
1:{B:"b"},
2:{C:"c"},
}
var result = Object.keys(data).map(function (key) {
return { [key]: data[key] };
});
console.log(result);
You can use Object.entries to get [key, value] pairs, and map them to an array of objects using computed property names:
const data = {
0:{A: 'a'},
1:{B: 'b'},
2:{C: 'c'}
};
const result = Object.entries(data).map(([key, value]) => ({ [key]: value }));
console.log(result);
I'm afraid you cant use to spread operator like in your example, however you can produce the desired output with reduce.
data = {
0:{A:'a'},
1:{B:'b'},
2:{C:'c'},
}
let resArr = Object.keys(data).reduce((arr, e) => {
arr.push({[e]: data[e]});
return arr;
}, []);
console.log(resArr);
let data = ['Uzbek sila', 'Hikmatbet', 'Aslamboi']
let spread = [...data]
console.log(spread)

Categories