Way to iterate through object to create array of objects - javascript

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

Related

Convery JS Object to array - keep key & value

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)

how can i convert array of objects to one object

I want to convert object1 to object2 dynamically because keys like apple and water and inside objects are not static.
const object1 = {
apple:[
{a:''},
{b:''}
],
water:[
{c:''},
{d:''}
]
}
convert to this form:
object2 = {
apple:{a:'',b:''},
water:{c:'',d:''}
}
Use Object.entries to iterate the key value pairs, then use Object.assign to merge the inner objects, and finally collect the generated pairs back into one object with Object.fromEntries:
const object1 = {apple:[{a:''},{b:''}],water:[{c:''},{d:''}]}
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, arr]) =>
[key, Object.assign({}, ...arr)]
)
);
console.log(object2);
const object1 = {
apple:[
{a:''},
{b:''}
],
water:[
{c:''},
{d:''}
]
}
let object={}
Object.keys(object1).forEach((item)=>{
let obj={};
object1[item].map((e)=>{
obj={...obj,...e};
});
object[item]=obj;
})
console.log(object)

Lodash move objects under a key part of same object

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

How to return a modified object after updating all the values in it?

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

Parsing and Convert Data type into Json in javascript

I have variable that contain array inside, when i was tried to print it with javascript console.log(res) show like this:
res = [{sakti: "23"},{Baim: "20"},{Jaka: "18"}]
How i suppose to do, if i want to change the data type into like this:
res = [{name: "sakti", y: 23},{name: "Baim", y: 20},{name: "Jaka", y: 18}]
my current code:
this.categoryservice.getRole().subscribe((res)=>{
console.log(res);
})
You can use map and Object.keys
let res = [{sakti: "23"},{Baim: "20"},{Jaka: "18"}]
let op = res.map(e=>{
let key = Object.keys(e)[0]
return { name: key, y: +e[key] }
})
console.log(op)
You can do this with Array.map, Object.entries and destructuring assignment:
const data = [{sakti: "23"}, {Baim: "20"}, {Jaka: "18"}];
const result = data.map(item => {
const [key, value] = Object.entries(item)[0];
return { name: key, y: value };
});
console.log(result);
Array.from is another way of mapping the object array into a new array of objects by using the second mapping argument. Object.keys & Object.values can be used to construct the new object by taking the [0] position from the key array which will be the name and [0] from the value array which will be the y key.
const res = [{sakti: "23"},{Baim: "20"},{Jaka: "18"}]
const arrayConv = Array.from(res, obj => { return {"name":Object.keys(obj)[0], "y":Object.values(obj)[0] } });
console.log(arrayConv);
you can use map and object.entries for this
var res = [{sakti: "23"},{Baim: "20"},{Jaka: "18"}]
var result = res.map((i)=>{
let obj = Object.entries(i);
return {'name': obj[0][0], 'y': obj[0][1]};
});
console.log(result);
With the new experimental flatMap() you can create a generic approach (in case one of your object have more than one key:val pair):
const res = [{sakti: "23", foo: "33"},{Baim: "20"},{Jaka: "18"}];
let mapped = res.flatMap(o => Object.entries(o).map(([k, v]) => ({name: k, y: +v})));
console.log(mapped);
But, you can always use reduce() for this too:
const res = [{sakti: "23", foo: "33"},{Baim: "20"},{Jaka: "18"}];
let mapped = res.reduce(
(acc, o) => acc.concat(Object.entries(o).map(([k, v]) => ({name: k, y: +v}))),
[]
);
console.log(mapped);

Categories