How to convert JSON Object into key value pair in JS? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
{"1":"val1","2":"val2","3":"val3"}
i want it to converted like this:
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
little Help Please would be much appricated

You can't use the same key name in one object.
instead you can do this.
const origin = {"1":"val1","2":"val2","3":"val3"}
const converted = Object.entries(origin).map( ([key,value]) => ({id: key, value }) );
console.log(converted);

What you have posted is invalid.
What you might want is:
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Object.entries(object));
// or
console.log(Object.keys(object).map(i => ({Id: i, value: object[i]})));

You could use a loop over Object.entries.
E.g. something like:
const newObjArr = [];
for(let [key, value] of Object.entries(obj)){
newObj.push({Id: key, value});
}
The above would return an array of objects, but I'm sure you can amend it to your particular use case.

const data = {"1":"val1","2":"val2","3":"val3"};
const result = Object.keys(data).map((key) => ({ id: key, value: data[key] }));
The result will be [{ id: "1", value: "val1" }, { id: "2", value: "val2" }, { id: "3", value: "val3" }]

As pointed out this is invalis. If you want to convert it if would look like this:
[{"Id":"1","value":"val1"},{"Id":"2","value":"val2"},{"Id":"3","value":"val3"}]
You can make an function that converts this.
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Convert(object));
function Convert(obj){
return Object.keys(obj).map(i => ({Id: i, value: obj[i]}));
}

You cannot do this. Object is a unique key value pair.
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
Suppose you want to merge two object and What if both the object has same key, it simply merge the last objects value and have only one key value.

You can convert your large object to several small objects and store them in an array as this snippet shows. (It could be much shorter, but this verbose demo should be easier to understand.)
// Defines a single object with several properties
const originalObject = { "1" : "val1", "2" : "val2", "3" : "val3" }
// Defines an empty array where we can add small objects
const destinationArray = [];
// Object.entries gives us an array of "entries", which are length-2 arrays
const entries = Object.entries(originalObject);
// `for...of` loops through an array
for(let currentEntry of entries){
// Each "entry" is an array with two elements
const theKey = currentEntry[0]; // First element is the key
const theValue = currentEntry[1]; // Second element is the value
// Uses the two elements as values in a new object
const smallObject = { id: theKey, value: theValue };
// Adds the new object to our array
destinationArray.push(smallObject);
} // End of for loop (reiterates if there are more entries)
// Prints completed array of small objects to the browser console
console.log(destinationArray);

const obj = {"1":"val1","2":"val2","3":"val3"}
const newObject = Object.keys(obj).map(e => {
return {ID: e , value : obj[e] }
});
console.log(newObject); // [ { ID: '1', value: 'val1' },
{ ID: '2', value: 'val2' },
{ ID: '3', value: 'val3' } ]
it will give u an array of object, later u need to convert it to object and flat the object:
How do I convert array of Objects into one Object in JavaScript?
how to convert this nested object into a flat object?

Related

Create an array of array's of object from Nested Objects

Suppose We have an Array with array of objects like
let array = [
[{value:'a',somepros:"old"}],
[{value:'d',somepros:"old"}],
[{value:'b',somepros:"old"}]
];
And we have nestedObj like
let obj ={
"a":{
"count":2
},
"b":{
"count":2
},
"c":{
"count":1
},
"e":{
"count":1
}
};
Now What I want is basically Using nested object i want to check the array's of object's array value if it exist or not and want to create an array as decleared above. Here the count in object is number no.of times the Array of object will appear in above array but. Suppose count is 2 for object proprerty "a" there is already an array of object exist having value "a". i want another array to be pushed number of time's the count but already exist 1 so 1 more time i will add it.
What I need is from Obj:
NewArr =[
[{value:'a',somepros:"old"}],
[{value:'a',somepros:"newpushed"}],
[{value:'b',somepros:"old"}],
[{value:'b',somepros:"newpushed"}],
[{value:'c',somepros:"newpushed"}],
[{value:'e',somepros:"newpushed"}],
];
The question doesn't really seems to make much sense in my opinion, but here it is:
let array = [
[{value:'a',somepros:"old"}],
[{value:'d',somepros:"old"}],
[{value:'b',somepros:"old"}]
],
obj ={
"a":{
"count":2
},
"b":{
"count":2
},
"c":{
"count":1
},
"e":{
"count":1
}
};
const res = [];
// loop each entry from obj.
for (const [key, {count}] of Object.entries(obj)) {
// check whether the key exists in the original array.
const matched = array.find((arr) => arr[0].value === key);
// If it exists, push it.
if (matched) res.push(matched);
// then, add X elements "newpushed", where X is given by the count declared - 0 if matched doesn't exist, otherwise 1 (since an element already existed).
res.push(
...Array.from({length: (count - (matched ? 1 : 0))}, (_) => ([{ value: key, somepros: 'newpushed' }]))
);
}
console.log(res);
Comments in the snippet explains what is done.

Combine array of objects into a single object [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?
You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);

Checking existence of object in Array in Javascript based on a particular value

I have an array of objects, and want to add a new object only if that object doesn't already exist in the array.
The objects in the array have 2 properties, name and imageURL and 2 objects are same only if their name is same, and thus I wish to compare only the name to check whether the object exists or not
How to implement this as a condition??
Since you've not mentioned the variables used. I'll assume 'arr' as the array and 'person' as the new object to be checked.
const arr = [{name: 'John', imageURL:'abc.com'},{name: 'Mike', imageURL:'xyz.com'}];
const person = {name: 'Jake', imageURL: 'hey.com'};
if (!arr.find(
element =>
element.name == person.name)
) {
arr.push(person);
};
If the names are not same, the person object won't be pushed into the array.
You can use Array.find
let newObj={ name:'X',imageURL:'..../'}
if(!array.find(x=> x.name == newObj.name))
array.push(newObj)
You need to check it using find or similar functions like this:
const arr = [{ name: 1 }, { name: 2 }];
function append(arr, newEl) {
if (!arr.find(el => el.name == newEl.name)) {
arr.push(newEl);
}
}
append(arr, { name: 2 }); // won't be added
console.log(arr);
append(arr, { name: 3 }); // will be added
console.log(arr);

Creating a JavaScript function that filters out duplicate in-memory objects?

Okay, so I am trying to create a function that allows you to input an array of Objects and it will return an array that removed any duplicate objects that reference the same object in memory. There can be objects with the same properties, but they must be different in-memory objects. I know that objects are stored by reference in JS and this is what I have so far:
const unique = array => {
let set = new Set();
return array.map((v, index) => {
if(set.has(v.id)) {
return false
} else {
set.add(v.id);
return index;
}
}).filter(e=>e).map(e=>array[e]);
}
Any advice is appreciated, I am trying to make this with a very efficient Big-O. Cheers!
EDIT: So many awesome responses. Right now when I run the script with arbitrary object properties (similar to the answers) and I get an empty array. I am still trying to wrap my head around filtering everything out but on for objects that are referenced in memory. I am not positive how JS handles objects with the same exact key/values. Thanks again!
Simple Set will do the trick
let a = {'a':1}
let b = {'a': 1,'b': 2, }
let c = {'a':1}
let arr = [a,b,c,a,a,b,b,c];
function filterSameMemoryObject(input){
return new Set([...input])
}
console.log(...filterSameMemoryObject(arr))
I don't think you need so much of code as you're just comparing memory references you can use === --> equality and sameness .
let a = {'a':1}
console.log(a === a ) // return true for same reference
console.log( {} === {}) // return false for not same reference
I don't see a good reason to do this map-filter-map combination. You can use only filter right away:
const unique = array => {
const set = new Set();
return array.filter(v => {
if (set.has(v.id)) {
return false
} else {
set.add(v.id);
return true;
}
});
};
Also if your array contains the objects that you want to compare by reference, not by their .id, you don't even need to the filtering yourself. You could just write:
const unique = array => Array.from(new Set(array));
The idea of using a Set is nice, but a Map will work even better as then you can do it all in the constructor callback:
const unique = array => [...new Map(array.map(v => [v.id, v])).values()]
// Demo:
var data = [
{ id: 1, name: "obj1" },
{ id: 3, name: "obj3" },
{ id: 1, name: "obj1" }, // dupe
{ id: 2, name: "obj2" },
{ id: 3, name: "obj3" }, // another dupe
];
console.log(unique(data));
Addendum
You speak of items that reference the same object in memory. Such a thing does not happen when your array is initialised as a plain literal, but if you assign the same object to several array entries, then you get duplicate references, like so:
const obj = { id: 1, name: "" };
const data = [obj, obj];
This is not the same thing as:
const data = [{ id: 1, name: "" }, { id: 1, name: "" }];
In the second version you have two different references in your array.
I have assumed that you want to "catch" such duplicates as well. If you only consider duplicate what is presented in the first version (shared references), then this was asked before.

JavaScript: Dynamically generated object key [duplicate]

This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 5 years ago.
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
]
const output = []
Object.keys(cars).map((car) => {
output.push({
foo: cars[car].defaultCategory
})
})
console.log(output)
This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.
So if I replace push argument with
${cars[car].id}`: cars[car].defaultCategory
I get SyntaxError: Unexpected template string
What am I doing wrong?
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
];
const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));
console.log(result);
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.
This is how should be your code:
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
var cars = [{
'id': 'truck',
'defaultCategory': 'vehicle'
}];
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
console.log(output);

Categories