I am trying to convert an object (updatedConfig) to an array (configArray), while maintaining the same structure (and avoid further nesting).
I have tried declaring a new array const and using Object.entries to push the keys & values.
I am able to get the keys but am having trouble figuring out how to achieve the nesting of array.
const configArray = [];
Object.entries(updatedConfig).forEach(([key, value]) => {
configArray.push(key);
})
Here is the object in question:
You can try something like this using Object.entries and Array.map
const configObject = {
key1: 'value',
key2: 1,
key3: [1, 2, 3]
}
const configArray = Object.entries(configObject).map(([key, value]) => ({key, value}))
console.log(configArray)
Related
Suppose there is an array like this:
const a = [ {p:1}, {p:2}, {p:3} ];
Is it possible to destructure this array in order to obtain p = [1, 2, 3] ?
Because this does not work :
const [ ...{ p } ] = a; // no error, same as const p = a.p;
// p = undefined;
Edit
In response to all the answers saying that I need to use Array.prototype.map, I am aware of this. I was simply wondering if there was a way to map during the destructuring process, and the answer is : no, I need to destructure the array itself, then use map as a separate step.
For example:
const data = {
id: 123,
name: 'John',
attributes: [{ id:300, label:'attrA' }, { id:301, label:'attrB' }]
};
function format(data) {
const { id, name, attributes } = data;
const attr = attributes.map(({ label }) => label);
return { id, name, attr };
}
console.log( format(data) };
// { id:123, name:'John', attr:['attrA', 'attrB'] }
I was simply wondering if there was a way, directly during destructuring, without using map (and, respectfully, without the bloated lodash library), to retrive all label properties into an array of strings.
Honestly I think that what you are looking for doesn't exist, normally you would map the array to create a new array using values from properties. In this specific case it would be like this
const p = a.map(element => element.p)
Of course, there are some packages that have many utilities to help, like Lodash's map function with the 'property' iteratee
you can destructure the first item like this :
const [{ p }] = a;
but for getting all values you need to use .map
and the simplest way might be this :
const val = a.map(({p}) => p)
Here's a generalized solution that groups all properties into arrays, letting you destructure any property:
const group = (array) => array.reduce((acc,obj) => {
for(let [key,val] of Object.entries(obj)){
acc[key] ||= [];
acc[key].push(val)
}
return acc
}, {})
const ar = [ {p:1}, {p:2}, {p:3} ];
const {p} = group(ar)
console.log(p)
const ar2 = [{a:2,b:1},{a:5,b:4}, {c:1}]
const {a,b,c} = group(ar2)
console.log(a,b,c)
I have an JSON object like
datas = [
{"id":1,"name":"Test","age":24},
{"id":2,"name":"Test1","age": 30}
]
I want to modify the JSON object like below
datas = [
{"1":{"name":"Test","age":24}},
{"2":{"name":"Test1","age": 30}}
]
I want to do the same using lodash . I can understand map over the data and create a new object should fix this
updated_data=[]
_.map datas, (data) ->
Obj = {}
Obj[data.id] = data
updated_data.push(Obj)
But I am looking for lodash way of achieving the same .
Use Array.map() (or _.map()) with destructuring and object rest (...):
const datas = [{"id":1,"name":"Test","age":24}, {"id":2,"name":"Test1","age": 30}]
const result = datas.map(({ id, ...o }) => ({ [id]: o }))
console.log(result)
With lodash you can do the same, but instead of destructuring use _.omit() to remove the id from the original object, and use _.zipObject() combine it with the id:
const datas = [{"id":1,"name":"Test","age":24}, {"id":2,"name":"Test1","age": 30}]
const result = _.map(datas, o => _.zipObject([o.id], [ _.omit(o, 'id')]))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
I think you don't need to use an extra library for this. This way you can achieve the desired result:
datas.map((item) => {
const { id, ...rest } = item;
return {
id: rest,
};
});
Basically I have an enum describing status
status = {1: "new", 2: "working" ... }
and I need to take it from that to something like
status = [{1: "new"}, {2: "working"} ...]
in a clean way ... i.e.
something readable, (maybe) simple and reliable. Currently I am not sure how to go about this ... maybe go through the object and "map" each pair to a brand new object in an array? Sounds bad.
Object.entries(data).map(([key, value]) => ({[key]: value}))
The result of the map is the array, what you want.
Or:
const arrayData = [];
for (const key in data) {
arrayData.push({[key]: data[key]})
}
iterate on objects dynamicly:
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
const { object } = require("prop-types")
const status = { 1: "new", 2: "working" }
const statusUpdate = Object.entries(status).map(([key, value]) => ({ [key]: value }))
console.log(statusUpdate);
I have an object that I want to use the keys as keys in a new object and the value into a child object. How could I go from A to Z?
const a = {key1: 'text', key2: 'text2'}
const z = [{ key1: { similarTo: 'text' } }, {key2: {similarTo: 'test2'}}]
You can use Object.entries and Array.prototype.map in order to achieve it:
const a = {key1: 'text', key2: 'text2'};
const z = Object.entries(a).map(([k, v]) => ({ [k]: { similarTo: v } }));
console.log(z);
I need to add single quotes to all the values in an object that looks like this:
{name: "testUser", type: "regular"}
The object needs to look like the following:
{name: "'testUser'", type: "'regular'"}
I'm using Object.values to achieve this:
Object.values(targetObject).map(value => value = `'${value}'`)
Except it's not exactly updating targetObject. What would be the correct way to achieve this?
To update the original object, you'll need the key. Use Object.entries() to get the key and value, iterate with Array.forEach(), and each key with the new value:
const targetObject = {name: "testUser", type: "regular"}
Object.entries(targetObject) // get an array of [key, value] pairs
.forEach(([k, v]) => targetObject[k] = `'${v}'`) // update the original object keys
console.log(targetObject)
You can use Object.entries to iterate through all the entries in the object and update them:
const obj = {name: "testUser", type: "regular"};
for (let [key, value] of Object.entries(obj)) {
obj[key] = `'${value}'`;
}
console.log(obj);
You can you for..in to loop through properties of the object.
const obj = {name: "testUser", type: "regular"}
for (let k in obj){
obj[k] = `'${obj[k]}'`
}
console.log(obj)
You could map new objects and collect them to a single object.
var object = { name: "testUser", type: "regular" },
updated = Object.assign(...Object.entries(object).map(([k, v]) => ({ [k]: `'${v}'` })));
console.log(updated);