Delete property and its values in all the object - javascript

I'm a beginner in javaScript, I have this object MyGraph:
const MyGraph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 },
};
I want to delete property "a" and its values in other properties as well to get this result:
const MyGraph = {
b: { c: 7, d: 8 },
c: { b: 7, d: 4, e: 8 },
};
I tried like this:
for(let XXX of Object.keys(MyGraph)){
console.log(XXX.a);
delete XXX.a;
}
the result of execution:
undefined
undefined
undefined
any help!

You could use a recursive algorithm :
function del_entries(key, obj) {
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
// Or with Object.hasOwn, not fully supported by old browsers but more up to date
/*
if (Object.hasOwn(obj, key)) {
delete obj[key]
}
*/
Object.values(obj).forEach(o=> del_entries(key, o))
}
const MyGraph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 },
};
del_entries("a", MyGraph);
console.log(MyGraph)

In your code XXX is the key. You need to do graph[XXX] to access the actual object. So instead of XXX.a you should do graph[XXX].a. But this only accounts for objects in graph that have an the key a. You also need to account for key a in graph. Please see the code below. Its a rudimentary example.
If you have one level of nesting then you can use then you can use the code below.
const mygraph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 },
};
console.log(mygraph);
function deletePropAndValuesOf(key, graph) {
for (const k of Object.keys(graph)) {
if (k === key) {
delete graph[key];
} else {
if (key in graph[k]) {
delete graph[k][key]
}
}
}
}
deletePropAndValuesOf("a", graph);
console.log(mygraph);
You can copy the code to a .js file and run it using node. e.g.

Ive used object destructuring to remove the first array with an a, but could not figure out how to do all the a's's but the code below might help?
const MyGraph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 }};
const {a, ...newMyGraph} = MyGraph;
// output
console.log(newMyGraph)
returns
b: {
a: 5,
c: 7,
d: 8
},
c: {
a: 2,
b: 7,
d: 4,
e: 8
}
}

Related

How to reassign values in a js object based on the values present in an object within the same object?

I have an array of objects in the following form-
let result = [
{
a: 1,
b: 2,
c: 3,
newValues: {
a: 10,
b: 20,
c: 30
}
},
{
d: 4,
e: 5,
f: 6,
newValues: {
d: 40,
e: 50,
f: 60
}
}
]
And want to convert it to following format -
let result = [
{
a: 10,
b: 20,
c: 30,
},
{
d: 40,
e: 50,
f: 60
}
]
But have been unable to do so.
Any help for converting the older array to the new one will be very much appreciated.
A simple map will do it
let result = [
{
a: 1,
b: 2,
c: 3,
newValues: {
a: 10,
b: 20,
c: 30
}
},
{
d: 4,
e: 5,
f: 6,
newValues: {
d: 40,
e: 50,
f: 60
}
}
]
let data = result.map( r => r.newValues)
console.log(data)
The problem by mapping only the r.newValues is you can potentially lost data that never changed and are not in newValues.
const result = [
{
a: 1,
b: 2,
c: 3,
newValues: {
a: 10,
b: 20,
c: 30
}
},
{
d: 4,
e: 5,
f: 6,
newValues: {
d: 40,
e: 50
}
}
];
const updates = result.map(element => {
const {newValues, rest} = element;
delete element.newValues;
return {...element, ...newValues};
});
console.log(updates);
It will work even if a value of newValues was not present into newValues.
The following answer is roughly equivalent to the one by JStw, with two key differences:
It uses Underscore instead of spread syntax;
It does not modify the elements of result.
This means that code is easier to reason about and potentially safer. Also, you don't need polyfills for the spread syntax.
const result = [
{
a: 1,
b: 2,
c: 3,
newValues: {
a: 10,
b: 20,
c: 30
}
},
{
d: 4,
e: 5,
f: 6,
newValues: {
d: 40,
e: 50
}
}
];
const updates = _.map(result, element =>
_.chain(element)
.omit('newValues')
.extend(element.newValues)
.value()
);
console.log(updates);
<script src="https://cdn.jsdelivr.net/npm/underscore#1.13.6/underscore-umd-min.js"></script>

Jest failing one function but not another

I am writing some daily challenges for my coding bootcamp and I am running into an issue on one problem. I wrote a function that combines objects and it works correctly. Here is what the problem prompt is
Prompt: Write a function named mergeObjects that accepts at least two objects as arguments, merges the properties of the second through n objects into the first object, then finally returns the first object. If any objects have the same property key, values from the object(s) later in the arguments list should overwrite earlier values.
Examples:
mergeObjects({}, {a: 1}); //=> {a: 1} (same object as first arg)
mergeObjects({a: 1, b: 2, c: 3}, {d: 4}); //=> {a: 1, b: 2, c: 3, d: 4}
mergeObjects({a: 1, b: 2, c: 3}, {d: 4}, {b: 22, d: 44}); //=> {a: 1, b: 22, c: 3, d: 44
My function
function mergeObjects(...obj) {
let obj1 = {}
obj.forEach(element => {
obj1 = {...obj1, ...element}
});
return obj1
}
Solution function
function mergeObjects1(target, ...objects) {
objects.forEach(function (obj) {
// using ES2015's 'for in' loop
for (var key in obj) {
target[key] = obj[key]
}
})
return target
}
In my eyes these two functions provide the same result. However, when I run my code through the jest test they created it fails on the first test. But the solution they provide, does not fail. The jest test is below.
describe('15-mergeObjects', function () {
it('returns same object', function () {
var obj = {}
expect(mergeObjects(obj, { a: 1 })).toBe(obj)
})
it('adds additional properties', function () {
expect(mergeObjects({ a: 1, b: 2, c: 3 }, { d: 4 })).toEqual({
a: 1,
b: 2,
c: 3,
d: 4
})
})
it('merges props from left to right', function () {
expect(
mergeObjects({ a: 1, b: 2, c: 3 }, { d: 4 }, { b: 22, d: 44 })
).toEqual({ a: 1, b: 22, c: 3, d: 44 })
})
})
describe('15-mergeObjects', function () {
it('returns same object', function () {
var obj = {}
expect(mergeObjects1(obj, { a: 1 })).toBe(obj)
})
it('adds additional properties', function () {
expect(mergeObjects1({ a: 1, b: 2, c: 3 }, { d: 4 })).toEqual({
a: 1,
b: 2,
c: 3,
d: 4
})
})
it('merges props from left to right', function () {
expect(
mergeObjects1({ a: 1, b: 2, c: 3 }, { d: 4 }, { b: 22, d: 44 })
).toEqual({ a: 1, b: 22, c: 3, d: 44 })
})
})
Can anyone provide an explanation as to why the solution function passes while my function does not?
While the results look the same, the two functions are slightly different.
In your function, you are creating a new object and then adding to it all of the required properties.
In the solution function, they are adding properties to the original target object and then returning it.
The returned objects from both functions will have the same keys and the same values, but different references, so they are not considered the same object in JavaScript.
In the test
expect(mergeObjects1(obj, { a: 1 })).toBe(obj)
.toBe() checks whether two objects are the same (identity), therefore it fails the case of your function.
Note that there is a different test, .toEqual(), which checks whether two objects have the same keys and the same values (but possibly different references). Your function would pass this test
expect(mergeObjects1(obj, { a: 1 })).toEqual(obj)

Rename a subkey of an object with ES6

I have a JS object of the following structure:
let data = {
Apples: {
A: 2,
B: 9
},
Oranges: {
C: 4,
D: 8
},
Bananas: {
E: 3,
F: 2
},
Peaches: {
G: 8,
H: 4
},
Pears: {
I: 10,
J: 10
},
Melons: {
K: 4,
L: 7
}
};
I need to rename the subkey dynamically with JS.
For example, I need to rename the key A into New name.
What is the best ES6-enabled way to do it?
I tried to loop through the object using a simple for loop and generate a new object with a renamed key, but it's indeed not the most efficient way!
What about this?
I'm not generating a new object, but adding the new properties to the existing one and deleting the original ones.
let data = {
Apples: {
A: 2,
B: 9
},
Oranges: {
C: 4,
D: 8
},
Bananas: {
E: 3,
F: 2
},
Peaches: {
G: 8,
H: 4
},
Pears: {
I: 10,
J: 10
},
Melons: {
K: 4,
L: 7
}
};
for (let key1 in data) {
const e = data[key1];
for (let key2 in e) {
e["New Name for " + key2] = e[key2];
delete e[key2];
}
}
console.log(data);

How to reshaping Data in Javascript from array to object without losing some of the data

I am trying to add the key to each so that I can be able to easy make a multi scatter plot in d3. . I am not sure how to do it.
EDIT: TO CLARIFY what I meant.
Data:
var dataOriginal = {
Apples: [{"A":4,"B":null,"C":null,"D":2}, {"A":5,"B":null,"C":3,"D":2}],
Oranges: [{"A":3,"B":1,"C":4,"D":4.3}],
Jackfruit: [{"A":5,"B":4,"C":4,"D":3}],
Avocado: [{"A":null,"B":33,"C":2,"D":9.66}],
Pomegranate: [{"A":5,"B":3.5,"C":null,"D":6}]
}
Function:
const data = Object.keys(dataOriginal).map((key) => {
const temp = {...dataOriginal[key]};
temp.key = key;
return temp;
});
Results:
0:
0: {A: 4, B: null, C: null, D: 2}
1: {A: 5, B: null, C: 3, D: 2}
key: "Apples"
__proto__: Object
1:
0: {A: 3, B: 1, C: 4, D: 4.3}
key: "Oranges"
__proto__: Object
2:
0: {A: 5, B: 4, C: 4, D: 3}
key: "Jackfruit"
__proto__: Object
3:
0: {A: null, B: 33, C: 2, D: 9.66}
key: "Avocado"
__proto__: Object
4: {0: {…}, key: "Pomegranate"}
Desired results
: {A: 4, B: null, C: null, D: 2, key: "Apples"}
1: {A: 3, B: 1, C: 4, D: 4.3, key: "Oranges"}
2: {A: 5, B: 4, C: 4, D: 3, key: "Jackfruit"}
3: {A: null, B: 33, C: 2, D: 9.66, key: "Avocado"}
4: {A: 5, B: 3.5, C: null, D: 6, key: "Pomegranate"}
5: {A:5,B:null,C:3,D:2, key: "Apples"}
You need to reduce the object to get a single object with added values.
const
addByKey = array => array.reduce((a, b) => {
Object.entries(b).forEach(([k, v]) => a[k] = (a[k] || 0) + v);
return a;
}, {}),
dataOriginal = { Apples: [{ A: 4, B: null, C: null, D: 2 }, { A: 5, B: null, C: 3, D: 2 }], Oranges: [{ A: 3, B: 1, C: 4, D: 4.3 }], Jackfruit: [{ A: 5, B: 4, C: 4, D: 3 }], Avocado: [{ A: null, B: 33, C: 2, D: 9.66 }], Pomegranate: [{ A: 5, B: 3.5, C: null, D: 6 }] }
data = Object.keys(dataOriginal).map((key) => ({ ...addByKey(dataOriginal[key]), key }));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For getting single object with same keys, you could map the objects, add the key and get a flat array.
const
dataOriginal = { Apples: [{ A: 4, B: null, C: null, D: 2 }, { A: 5, B: null, C: 3, D: 2 }], Oranges: [{ A: 3, B: 1, C: 4, D: 4.3 }], Jackfruit: [{ A: 5, B: 4, C: 4, D: 3 }], Avocado: [{ A: null, B: 33, C: 2, D: 9.66 }], Pomegranate: [{ A: 5, B: 3.5, C: null, D: 6 }] }
data = Object
.keys(dataOriginal)
.flatMap(key => dataOriginal[key].map(o => ({ ...o, key })));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The reason why {"A":5,"B":null,"C":3,"D":2} is missed is because, index 0 is hardcoded in the code.
const temp = {...dataOriginal[key][0]};
Alternate solution:
var dataOriginal = {
Apples: [{"A":4,"B":null,"C":null,"D":2}, {"A":5,"B":null,"C":3,"D":2}],
Oranges: [{"A":3,"B":1,"C":4,"D":4.3}],
Jackfruit: [{"A":5,"B":4,"C":4,"D":3}],
Avocado: [{"A":null,"B":33,"C":2,"D":9.66}],
Pomegranate: [{"A":5,"B":3.5,"C":null,"D":6}]
}
const myData =[]
Object.keys(dataOriginal).map((key) => {
for (let i = 0; i < dataOriginal[key].length; i++) {
myData.push({...dataOriginal[key][i], key})
}
})
console.log(myData)

Adding a new element to an object in an array

Lets say I have and array made up of objects:
var points = [
{ id: 1, a: 0, b: 3 },
{ id: 2, a: 4, b: -1 },
{ id: 3, a: -1, b: 5 },
{ id: 4, a: 41, b: 2 },
{ id: 5, a: 69, b: 3 },
]
I want to iterate through each item and add a + b to get a new item d. I then want to add d within each object in the array to get a new value. When I try the below, it just adds 5 extra objects rather than appending the new element (key=value, ex: d: 3) to each individual object. What am I doing wrong here?
points.forEach((item) => {
var d = Math.abs(item.x) + Math.abs(item.y);
console.log(d);
points.item.push('d: ' + d);
});
Try following
var points = [{ id: 1, a: 0, b: 3 },{ id: 2, a: 4, b: -1 },{ id: 3, a: -1, b: 5 },{ id: 4, a: 41, b: 2 },{ id: 5, a: 69, b: 3 }];
points.forEach(o => o.d = Math.abs(o.a) + Math.abs(o.b));
console.log(points);
#jcbridwe, you can use assign() method on Object to add missing property from source object to target object.
Please have a look at the below code.
Try the below code online at http://rextester.com/EPHYV10615.
var points = [
{ id: 1, a: 0, b: 3 },
{ id: 2, a: 4, b: -1 },
{ id: 3, a: -1, b: 5 },
{ id: 4, a: 41, b: 2 },
{ id: 5, a: 69, b: 3 },
]
for(var index in points){
var a = points[index].a;
var b = points[index].b;
Object.assign(points[index], {d: a+b});
}
console.log(points);
» Output
[ { id: 1, a: 0, b: 3, d: 3 },
{ id: 2, a: 4, b: -1, d: 3 },
{ id: 3, a: -1, b: 5, d: 4 },
{ id: 4, a: 41, b: 2, d: 43 },
{ id: 5, a: 69, b: 3, d: 72 } ]
Mutable approach:
points.forEach(o => o.d = o.a + o.b);
Immutable approach:
const newPoints = points.map(o => Object.assign({}, o, {d: o.a + o.b}))

Categories

Resources