How to rename object property in javascript? - javascript

I have got a nested object. I want to rename the object properties.
{
0: {value: "can_view"},
1: {value: "can_create"}
}
My output would be:
{
user_can: "can_view",
user_view: "can_create"
}

You can do that in three steps:
Get the entries using Object.entries()
Use map() on it and replace each key with the desired value
Convert it back to object using Object.fromEntries()
const obj = {
0: {value: "can_view"},
1: {value: "can_create"}
}
const res = Object.fromEntries(Object.entries(obj).map(([k, v]) => [v.value, v.value]));
console.log(res)

Improving Maheer Ali's answer.
Here you go:
const obj = {
0: {value: "can_view"},
1: {value: "can_create"}
}
var res = Object.fromEntries(Object.entries(obj).map(([k, v]) => [v.value.replace("can", "user"), v.value]));
var myResutls = JSON.stringify(res).replace(/"(\w+)"\s*:/g, '$1:');
console.log(myResutls);
alert(myResutls)
OUTPUT:
{
user_view: "can_view",
user_create: "can_create"
}

Related

How do I filter out an object with a given property?

Let's say that I have an array with objects like
const obj = [{value: 'prop1'}, {value: 'prop2', status: '401'}]
How do I filter out that object with status property so that it remains only the first object in array?
I tried
const result = obj.filter(o => o.status !== undefined) but it doesn't work.
Any help will be appreciated.
const obj = [{value: 'prop1'}, {value: 'prop2', status: '401'}];
let result = obj.filter( elem => !elem.status);
console.log(result);
const myArray = [{value: 'prop1'}, {value: 'prop2', status: '401'}]
const result = myArray.find(i => i.status);
console.log(result);
const obj = [{value: 'prop1'}, {value: 'prop2', status: '401'}];
const newObj = obj.filter(item=> !item.status);
console.log(newObj);

Implementing Lodash Invert

I'm working on a challenge that requires me to implement the .invert() method myself. Below is my solution but the expected outcome doesn't match with the actual outcome returned. Please see the second block below.
Implemented .invert() method:
const _ = {
invert(object) {
let newObject = {};
for (let key in object) {
const originalValue = object[key]
newObject = {
originalValue: key
}
}
return newObject;
}
};
Tested with below code:
var obj1 = { 'a': '1', 'c': '1', 'b': '2' };
console.log(_.invert(obj1));
And I expected to see below is returned:
{ '1': 'c', '2': 'b' }
Actually returned value was as below:
{ originalValue : 'c'}
I'm doing something terribly wrong, but can't figure out what... Can someone help?
Instead of assigning a new value for newObject every loop, try just adding a new key to the current object:
const _ = {
invert (object) {
let newObject = {};
for (let key in object) {
const originalValue = object[key];
newObject[originalValue] = key;
}
return newObject;
}
};
EDIT: as this has been accepted as the answer, I would like to mention that, personally, I like better the solution presented by Ori Drori.
That said, this answer is closer to the original implementation by the question author and I thought it was a better way to understand the necessary change. But if you, coming to this answer just for the code, I'd invite you to try understand and using Ori Drori's version.
Solve this using reduce.
var obj = { 'a': '1', 'c': '1', 'b': '2' };
const res = Object.entries(obj).reduce((a, [k, v]) => ({...a, [v]: k}), {});
console.log(res);
Convert to an array of pairs of [key, value] using Object.entries(), then map and and flip the pairs to [value, key]. Convert back to an object using Object.fromEntries():
const obj = { 'a': '1', 'c': '1', 'b': '2' };
const result = Object.fromEntries(
Object.entries(obj)
.map(([k, v]) => [v, k])
)
console.log(result);

How to determine if object is array-like and convert it into array?

I'm using dep-object-diff, which returns differences between two objects.
The problem is that if I have something like,
const objectA = {
fieldA: 5,
fieldB: ['123']
}
const objectB = {
fieldA: 5,
fieldB: ['123', '456']
}
Then it returns,
const diff = {
fieldB: {
0: '456'
}
}
When the required response object should be,
const diff = {
fieldB: ['456']
}
How can I detect if diff.fieldB is an array (dynamically, without hardcoding), and consequently convert it into one?
Edit
Thanks to #Nina Scholz, I ended up using her approach as the base. The problem which I caught with my data, however, was that the approach didn't work for strings. Anyway, I ended up implementing it as follows:
const diffs = {
fieldA: "SOME_STRING",
fieldB: {
3: '123',
5: '456'
},
};
const chronologize = (object) => {
let counter = 0;
for (let prop in object) {
if (object[prop]) {
object[counter] = object[prop];
delete object[prop];
counter++;
}
}
return object;
};
const result = Object.fromEntries(
Object.entries(diffs).map(([k, v]) =>
typeof v === 'string'
? [k, v]
: [k, Object.assign([], chronologize(v))]),
);
console.log(result);
You could get the entries, convert the array like object to array with Object.assign and an array as target and convert back to an object.
const
diff = { fieldB: { 0: '456' } },
result = Object.fromEntries(Object.entries(diff).map(([k, v]) => [k, Object.assign([], v)]));
console.log(result);

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

How to grab a object property from json with lodash?

I am getting my head around lodash for js and trying to select the object property with the name 'one' from this object by using the id key:
{
"one": {
"id":"peter",
"somevalue":1
},
"two": {
"id":"john",
"somevalue":1
}
}
So as a result I would like:
{
"id":"peter",
"somevalue":1
}
Sorry I updated the question:
How can I accomplish this with lodash returning this result based on the name in this case 'one' by using the key , id='peter'?
With Lodash (#1):
const value = _.find(obj, prop => prop.id === 'peter');
With Lodash (#2):
const value = _.find(obj, {id: 'peter'});
With Lodash (#3): (credit to hughes)
const value = _.find(obj, 'id', 'peter');
Plain JS:
const key = Object.keys(obj).find(key => obj[key].id === 'peter');
const value obj[key];
Future JS:
const value = Object.values(obj).find(prop => prop.id === 'peter');
More documentation on filter here: https://lodash.com/docs#filter
var obj = {
"one": {
"id":"peter",
"somevalue":1
},
"two": {
"id":"john",
"somevalue":1
}
};
console.log(_.filter(obj, {id:"peter"}));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Categories