0

I have this json object that hold some data, and I'm doing a search on that object and when the result match I want to save it to another object. What is the best way to do it.

I need some help copying the data I want to the new variable.

Here is what I have.

myjson = JSON.parse(jsonData);
for(var x=0; x<myjson.ROWCOUNT;x++){
    if(myjson.DATA.PARTNUMBER[x].search(regex) != -1){
        console.log(myjson.DATA.PARTNUMBER[x]);
    }
}

Where I have the console.log that display the partnumber, how can I make it so it copies all the content from the X row?

myjson has 4 columns (ID,PARTNUMBER,DESCRIPTION,PRICE) but I'm only searching on the partnumber. I need to copy all to the new json object.

thanks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ennio
  • 1,147
  • 2
  • 17
  • 34

3 Answers3

1

You can copy your object using clone function from that post How do I correctly clone a JavaScript object?

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

It copies your object not depending on its structure.

Community
  • 1
  • 1
Krzysiek
  • 98
  • 1
  • 4
0

myjson.DATA[x] is a reference to the object that contains the matched PARTNUMBER. Depending on what you want to do with it, you could it to an array for future accessing. E.g.:

myCopies = [];
myjson = JSON.parse(jsonData);
for(var x=0; x<myjson.ROWCOUNT;x++){
    if(myjson.DATA.PARTNUMBER[x].search(regex) != -1){
        console.log(myjson.DATA.PARTNUMBER[x]);
        myCopies.push(myjson.DATA[x]);
    }
}

// myCopies now contains references to all objects matched by partnumber
Benjamin Ray
  • 1,855
  • 1
  • 14
  • 32
-1

Simple way is to hard copy all your properties if there is a matched object

var myjson = JSON.parse(jsonData),
    output = [],
    matchedObj
;

for(var x=0; x<myjson.ROWCOUNT;x++){
    if(myjson.DATA.PARTNUMBER[x].search(regex) != -1){
        output.push({
            ID: myjson.DATA.ID[x],
            PARTNUMBER: myjson.DATA.PARTNUMBER[x],
            DESCRIPTION: myjson.DATA.DESCRIPTION[x],
            PRICE: myjson.DATA.PRICE[x]
        });
    }
}

console.log(output);

Another way, is to define a simple function to clone all properties of the matched object

var myjson = JSON.parse(jsonData),
    output = [],
    matchedObj,
    clone = function(data, i) {
        var copy = {};

        for(var attribute in data) {
            if (data.hasOwnProperty(attribute )) {
                copy[attribute] = data[attribute][i];
            }
        }

        return copy;
    }
;


for(var x=0; x<myjson.ROWCOUNT;x++){
    if(myjson.DATA.PARTNUMBER[x].search(regex) != -1){
        output.push(clone(myjson.DATA, x));
    }
}

console.log(output);
Mohamed Shaaban
  • 1,129
  • 6
  • 13