I have the following JSON object:
{
id: "id string",
test: {
everything inside test
},
rest_id: "rest_id string"
}
I want to re-format the object a bit so it is as follows:
{
everything inside test,
id: "rest_id string" // pulled from rest_id
}
and finally need to get the rid of the original id property. What is the best way for me to re-format this JSON object?
You can create a new object with the properties you want using a destructuring assignment
const before = {
id: "id string",
test: {
foo: 'foo',
bar: 'bar',
baz: 'baz',
id: 'i will be lost'
},
rest_id: "rest_id string"
}
const after = {
...before.test,
id: before.rest_id
}
console.log(after)
Note that if there are any id properties in test, they will be lost.
Use Object.assign to promote the contents of the inner object, then the delete operator to delete the inner object and the unwanted id key.
let input = {
id: "some string",
test: {
someKey: 'someValue'
},
rest_id: "some string"
}
input = Object.assign(input, input.test)
delete input.test
delete input.id
console.log(input)
You should first verify if obj and obj.test exist, if they do iterate through all properties in obj.test and write them to obj.
Then you can replace obj.id with obj.rest_id if it exists.
The old properties can be deleted safely.
let obj = {
id: "some string",
test: {
something: "hey hey hey",
something_else: "ok",
also_this: "alright"
},
rest_id: "some other string"
}
if (obj && obj.test) {
if(Object.keys(obj.test).length) {
Object.keys(obj.test).forEach((key, value) => {
obj[key] = value
});
}
delete obj.test
}
if (obj && obj.rest_id) {
obj.id = obj.rest_id
delete obj.rest_id
}
console.log(obj)
Related
I have the following code for adding getters to an object on the fly:
const obj = {};
const uni = { name1: ..., name2: ..., ...};
for(const nm in uni) {
const u = obj[nm] = {};
Object.defineProperty(u, 'value', {
configurable: true,
enumerable: true,
get: () => { return uni[nm] },
});
}
I want getters to return different values, so I want uni[nm] to be understood literary, i.e. the first getter would return uni.name1, the second uni.name2 etc.
How do I do that?
EDIT:
I want to dynamically create an object like this:
{
name1: { get value() { return uni.name1 }},
name2: { get value() { return uni.name2 }},
...
}
Don't use for..in. And you pretty much never need Object.defineProperty. That's all stone age JavaScript.
Instead use -
for..of to iterate over Object.keys.
get keyword to define a getter
const uni = { name1: "foo", name2: "bar" }
let obj = {}
for(const key of Object.keys(uni)) {
obj[key] = {
get value() {
return uni[key]
}
};
}
console.log(obj.name1.value) // "foo"
console.log(obj.name2.value) // "bar"
uni.name1 = "zzz"
console.log(obj.name1.value) // "zzz"
This can be expressed using array.reduce and -
object spread to extend the definition of an object
computed properties to define a dynamic key -
const uni = { name1: "foo", name2: "bar" }
const obj = Object.keys(uni).reduce(
(o, key) => {
return {...o, [key]: { get value() { return uni[key] }}} // extend
},
{} // initial object
)
console.log(obj.name1.value) // "foo"
console.log(obj.name2.value) // "bar"
uni.name1 = "zzz"
console.log(obj.name1.value) // "zzz"
You can achieve this by using the square bracket notation ([]) to dynamically access properties in the uni object, like this:
I need to check key exist in object of object. I have array of object and in every object i have one other object. I need to check the key is existing in object of object
var myarr = [{
hello: "world",
payload: {
kekek: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
},
{
hello: "world",
payload: {
qwe: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
}, {
hello: "world",
payload: {
qwe: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
},
{
hello: "world",
payload: {
asdf: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
}
]
let pp = myarr.payload.hasOwnProperty('eekey')
console.log(pp).
I need to check kekek in payload.
If I understood correctly, you want to check if every of object of your array contains a specific key in payload property. If so, you can use in operator to check if a property is present in a object. You can improve this snippet by checking if value is defined.
let key = 'kekek';
const everyObjectHasKey = myarr.every(item => item.payload && key in item.payload);
console.log(everyObjectHasKey);
In this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every , you can see more about every method for arrays
I am not comfortable with certain subtleties, and here are 2 days that I go around in circles, to carry out "manipulations" of Objects in javascript (NodeJS), I therefore appeal to your knowledge!
I send elements from a json as a parameter in a .js script.
in this script, I would like to process the elements sent as a parameter (by a loop), to add them to a list, then to be able to add others "manually", to finally get a "list" of the set with different additional information.
my "test" script where I simulate the parameters received and "try" to get this "list":
let params = JSON.parse('{ "100": 3, "101": 1 }') // simulate parameters
let lstObj = {} // content all the list obj
// only for the test
function foo(type) {
return "type is " + type;
}
function addToList(id, type) {
let obj = {
id: id,
type: type,
test: foo(type)
}
console.log('from addToList() -> ', obj);
return obj;
}
// process the Obj from parameters
let index = 0;
for (let [key, value] of Object.entries(params)) {
console.log("from Param: ", `${key} -> ${value}`, " or ", key, "->", value);
obj = addToList(key, value); // seem work
//lstObj.key = obj; // use 'key' not the key value
//lstObj.[key] = obj; // error
//lstObj.`${key}` = obj; // error
//lstObj.["999"] = obj; // error
//index++; lstObj.index = obj; // bad :)
lstObj.a999 = obj; // Work ! but how can a make it ?
}
console.log('\nResult -> ', lstObj);
// Now want to manualy add other Obj in the List, like this ?
// lstObj.999 = addToList("999", 3)
I would like to get a result like this:
{
"100": {id: 100, type: 1, test: 'Type is 1', ....}
"102": {id: 102, type: 3, test: 'Type is 3', ....}
"110": {id: 110, type: 1, test: 'Type is 1', ....}
"305": {id: 305, type: 2, test: 'Type is 2', ....}
}
The purpose of being able to subsequently retrieve the object of an element by a call like: "lstobj.101"
Thank's a lot !
What you need is to assign the key to the object.
Change this line
lstObj.a999 = obj; // Work ! but how can a make it ?
to
lstObj[key] = obj;
What this does is assign whatever value is contained by variable key to be a key in variable lstObj, then assign the value of obj as it's value.
For example
let key = 'exampleKey';
let value = 'exampleValue';
let obj = {};
obj[key]=value; //now object is { 'exampleKey': 'exampleValue' }
I have a set of object of object. For example
{
"123":{
id:123,
name:"abc"
},
"456":{
id:456,
name:"def"
},
"789":{
id:789,
name:"ghi"
}
}
I would like to know how to loop over my object and check if the value "def" exist in the object list?
Can I know how to loop through every iteration and only do decision ?? For example first iteration is abc then next is def then next is ghi . because abc and def is not same but when come to def and def it is same .Can I do action or logic after finish loop through every iteration ?
Use a for loop on the object to check that value exist in name property or not:
var obj = {
123: {
id: 123,
name: 'abc'
},
456: {
id: 456,
name: 'def'
},
789: {
id: 789,
name: 'ghi'
}
};
var checkVal = 'def';
let match = false;
for(var objKey in obj) {
if(obj[objKey].name === checkVal) {
match = true;
}
}
console.log('found ', match);
There are a couple of ways to loop through an object in Javascript, depending on what version you are using.
The basics of it Ankit talked about in his answer:
const search = {
"123":{
id:123,
name:"abc"
},
"456":{
id:456,
name:"def"
},
"789":{
id:789,
name:"ghi"
}
};
for(let key in search) {
if(search[key].name == 'def') {
console.log(search[key]);
}
}
If you are using a newer version of Javascript, you can do the following:
const search = {
"123":{
id:123,
name:"abc"
},
"456":{
id:456,
name:"def"
},
"789":{
id:789,
name:"ghi"
}
}
for(let obj of Object.values(search)){
if(obj.name==='def') console.log(obj);
}
// or, very similarly
for(let key of Object.keys(search)) {
let obj = search[key];
if(obj.name=='def') console.log(obj);
}
Or, lastly.
const search = {
"123":{
id:123,
name:"abc"
},
"456":{
id:456,
name:"def"
},
"789":{
id:789,
name:"ghi"
}
}
for(let [key, obj] of Object.entries(search)){
if(obj.name=='def') console.log('found on key ', key, 'value:', obj);
}
Note that the last one uses the destructuring assignment so that you do not need to use a placeholder variable simply to assign key and object/value out inside the loop.
Iam trying to push in array an object, but I get always error.
fCElements = [],
obj = {};
obj.fun = myFunction;
obj.id = 2;
fCElements.push ({
obj,
myid:2,
name:'klaus'
})
how I can push into array functions like "myFunction"?
Thanks
In the Object literal, you can only give key-value pairs. Your obj doesn't have any value.
Instead, you can do like this
var fCElements = [];
fCElements.push({
obj: {
fun: myFunction,
id: 2
},
myid: 2,
name: 'klaus'
});
Now, you are creating a new object, obj, on the fly, while pushing to the array. Now, your fCElements look like this
[ { obj: { fun: [Function], id: 2 }, myid: 2, name: 'klaus' } ]
You need to give your obj property a name (or a value).
var obj = {};
obj.fun = myFunction;
obj.id = 2;
fCElements.push ({
obj:obj,
myid:2,
name:'klaus'
});
The object you are pushing to the array seems off. It will try to push this object:
{
{fun: myfunction, id: 2},
myid: 2,
name: 'klaus'
}
Which is an invalid object since the first value has no key. You should do it like this instead:
fCElements.push ({
myObj:obj,
myid:2,
name:'klaus'
});