Categories
JavaScript Answers

How to print JSON data in JavaScript console.log?

To print JSON data in JavaScript console.log, we use the '%j' option.

For instance, we write

console.log("%j", jsonObj);

to call console.log with "%j" and the jsonObj object to print JSON objects with console.log.

Categories
JavaScript Answers

How to compare two arrays of objects, and exclude the elements who match values into new array in JavaScript?

To compare two arrays of objects,and exclude the elements who match values into new array in JavaScript, we use the filter and some methods.

For instance, we write

const result = result1.filter((o1) => !result2.some((o2) => o1.id === o2.id));

to call result1.filter with a callback that checks if result2 don’t have items that have o2 in result1‘s id that’s equal to o2 in result2‘s id.

Then an array with the objects in result1 where id property isn’t equal to objects in result2‘s id property are included.

Categories
JavaScript Answers

How to push object into array with JavaScript?

To push object into array with JavaScript, we use the push method.

For instance, we write

const nietos = [];
nietos.push({ "01": nieto.label, "02": nieto.value });

to call nietos.push with an object to append it has the last item of the nietos array.

Categories
JavaScript Answers

How to convert Map to array of object with JavaScript?

To convert Map to array of object with JavaScript, we use the spread operator and map.

For instance, we write

const myMap = new Map().set("a", 1).set("b", 2);
const arr = [...myMap].map(([name, value]) => ({ name, value }));
console.log(arr);

to create a map with the Map constructor.

Then we call set to add some key-value pairs.

Next, we spread myMap into an array of key-value pair arrays.

And then we call map to get the name and value and put them in an object.

Categories
JavaScript Answers

How to use JavaScript lodash push to an array only if value doesn’t exist?

To use JavaScript lodash push to an array only if value doesn’t exist, we use sets.

For instance, we write

const s = new Set();

s.add("hello");
s.add("world");
s.add("hello");

to create a set with the Set constructor.

And then we call add to add 'hello' and 'world'.

'hello' won’t be added a 2nd time since it already exists.